Hello I am trying to get the city name from my current location, but unfortunately I am not able to.
Could I know if there is a better way to do it ? Thank you Here is the code :
//Getting city name
try{
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
String city = addresses.get(0).getLocality();
Log.v(TAG, "City = " + city);
mLocationLabel.setText(city);
//System.out.println(addresses.get(0).getLocality());
}
} catch (IOException e){
Log.e(TAG, "Failed to get city name.", e);
Log.v(TAG, "Failed to get city name.");
}
I think the data of Geocoder depends on the location.
I would get rather many results for testing purpose. Like this:
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 10);
if (!addressList.isEmpty()) {
for (Address address : addressList) {
String result = address.getAdminArea() != null ? address.getAdminArea() : "?";
result += " | ";
result += address.getSubAdminArea() != null ? address.getSubAdminArea() : "?";
result += " | ";
result += address.getLocality() != null ? address.getLocality() : "?";
result += " | ";
result += address.getSubLocality() != null ? address.getSubLocality() : "?";
result += " | ";
result += address.getThoroughfare() != null ? address.getThoroughfare() : "?";
result += " | ";
result += address.getSubThoroughfare() != null ? address.getSubThoroughfare() : "?";
Log.i(TAG, result);
}
}
} catch (IOException e) {
Log.e(TAG, "Failed Geocoding.");
}
And I have verified Geocoder's data is not so certain.