I am writing an android application to get current location city name, I get the latitude and longitude right, but I can't get the city name. here is my code :
// To get City-Name from coordinates
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: " + cityName;
editLocation.setText(s);
There are two ways to get the current location of any Android device: Android's Location Manager API. Fused Location Provider: Google Play Services Location APIs.
The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.
The short story is you need to do: Geocoder geocoder = new Geocoder(this, Locale. getDefault()); List<Address> addresses = geocoder. getFromLocation(lat, lng, 1);
public String getLocationName(double lattitude, double longitude) {
String cityName = "Not Found";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
10);
for (Address adrs : addresses) {
if (adrs != null) {
String city = adrs.getLocality();
if (city != null && !city.equals("")) {
cityName = city;
System.out.println("city :: " + cityName);
} else {
}
// // you should also try with addresses.get(0).toSring();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
You would have to use the geocode api in this case. This returns you a json response parse it and 'locality' is the city you require. Here is the proper documentation for it.
http://maps.google.com/maps/api/geocode/json?address=19.701989,72.774733&sensor=false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With