Kemo Kemo - 4 months ago 36
Java Question

Geocoder often returns null vallues in Android

I am trying to pass geocoder values from MapFragment to LocationDetailsActivity.

I get the correct values for lat and lng, but when I try to display any of the other values, most of the times I get null values instead of the city and zip (but not always), while a lot of the times I get the correct country and state (also not always).

MapFragment Code:

// Set default latitude and longitude
double latitude = 15.4825766;
double longitude = -5.0076589;

// Get latitude and longitude of the current location and a LatLng object
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}

mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

@Override
public void onMapLongClick(LatLng arg0) {

Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(arg0.latitude, arg0.longitude, 1);
if (allAddresses.size() > 0 && allAddresses != null) {
Address address = allAddresses.get(0);
Intent intent = new Intent(getActivity(), LocationDetailsActivity.class);
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
intent.putExtra("city", allAddresses.get(0).getLocality());
intent.putExtra("zip", allAddresses.get(0).getPostalCode());
intent.putExtra("state", allAddresses.get(0).getAdminArea());
intent.putExtra("country", allAddresses.get(0).getCountryName());
startActivity(intent);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});


LocationDetailsActivity Code:

Bundle bundle = getIntent().getExtras();
double lat = bundle.getDouble("latitude");
double lng = bundle.getDouble("longitude");
String city = intent.getStringExtra("city");
String zip = intent.getStringExtra("zip");
String state = intent.getStringExtra("state");
String country = intent.getStringExtra("country");

// I display my values here
mFirstValueDisplay.setText(String.valueOf(city));
mSecondValueDisplay.setText(String.valueOf(zip));

Answer

Android's geocoding api is pretty unreliable up-to my experience, I usually make a request to the Google's geocoding webservices on Url : "https://maps.googleapis.com/maps/api/geocode" (If you are familiar with retrofit)

@GET("/json")
    void reverseGeoCode(@Query("latlng") String latlng, @Query("language") String language,
                        @Query("key") String key, Callback<ReverseGeoCode> callback);

latlng The latitude and longitude you want to reverse geocode.

language language of the geocoded response

key Your Api key

Go here for more info