ภาพรวม
ตัวอย่างนี้สาธิตวิธีการแปลงพิกัดละติจูดและลองจิจูด (Latitude/Longitude) ให้เป็นที่อยู่ที่อ่านง่าย โดยใช้ Geocoder และ Location Service ใน Android
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ใหม่ใน Android Studio ตามปกติ
ขั้นตอนที่ 2: จัดทำ Layout (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16sp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="@+id/btnShowAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="แสดงที่อยู่"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tvAddress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="134dp"
android:layout_alignParentEnd="true" />
</RelativeLayout>
ขั้นตอนที่ 3: สร้างคลาส AppLocationService.java
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
@SuppressLint("Registered")
public class AppLocationService extends Service implements LocationListener {
protected LocationManager locationManager;
Location location;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
public AppLocationService(Context context) {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
@SuppressLint("MissingPermission")
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
// ... implement LocationListener methods
}
ขั้นตอนที่ 4: สร้างคลาส LocationAddress.java
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
class LocationAddress {
private static final String TAG = "LocationAddress";
static void getAddressFromLocation(final double latitude,
final double longitude, final Context context, final Handler handler) {
Thread thread = new Thread() {
@Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude + "\n\nAddress:\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + " Longitude: " + longitude + "\n Unable to get address for this lat-long.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
ขั้นตอนที่ 5: เขียนโค้ด MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnShowAddress;
TextView tvAddress;
AppLocationService appLocationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvAddress = findViewById(R.id.tvAddress);
appLocationService = new AppLocationService(MainActivity.this);
btnShowAddress = findViewById(R.id.btnShowAddress);
btnShowAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
double latitude = 13.1000727;
double longitude = 80.2126274;
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(latitude, longitude,
getApplicationContext(), new GeoCodeHandler());
showSettingsAlert();
}
});
}
// ... GeoCodeHandler และ showSettingsAlert methods
}
ขั้นตอนที่ 6: กำหนดสิทธิ์ใน AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
การทดสอบ
รันแอปกดปุ่ม "แสดงที่อยู่" จะแสดงที่อยู่ที่แปลงจากพิกัดที่กำหนดไว้