How to reverse Geocode in google maps api 2 android
Use Geocoder:
Geocoder geoCoder = new Geocoder(context);
List<Address> matches = geoCoder.getFromLocation(latitude, longitude, 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
This is how it works for me..
MarkerOptions markerOptions;
Location myLocation;
Button btLocInfo;
String selectedLocAddress;
private GoogleMap myMap;
LatLng latLng;
LatLng tmpLatLng;
@Override
public void onMapLongClick(LatLng point) {
// Getting the Latitude and Longitude of the touched location
latLng = point;
// Clears the previously touched position
myMap.clear();
// Animating to the touched position
myMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Creating a marker
markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Adding Marker on the touched location with address
new ReverseGeocodingTask(getBaseContext()).execute(latLng);
//tmpLatLng = latLng;
btLocInfo.setEnabled(true);
btLocInfo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
double[] coordinates={tmpLatLng.latitude/1E6,tmpLatLng.longitude/1E6};
double latitude = tmpLatLng.latitude;
double longitude = tmpLatLng.longitude;
Log.i("selectedCoordinates", latitude + " " + longitude);
Log.i("selectedLocAddress", selectedLocAddress);
}
});
}
private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
Context mContext;
public ReverseGeocodingTask(Context context){
super();
mContext = context;
}
// Finding address using reverse geocoding
@Override
protected String doInBackground(LatLng... params) {
Geocoder geocoder = new Geocoder(mContext);
double latitude = params[0].latitude;
double longitude = params[0].longitude;
List<Address> addresses = null;
String addressText="";
try {
addresses = geocoder.getFromLocation(latitude, longitude,1);
Thread.sleep(500);
if(addresses != null && addresses.size() > 0 ){
Address address = addresses.get(0);
addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
}
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
selectedLocAddress = addressText;
return addressText;
}
@Override
protected void onPostExecute(String addressText) {
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(addressText);
// Placing a marker on the touched position
myMap.addMarker(markerOptions);
}
}