Reputation: 567
I am writing this code to get the city name of your current location using my longitude and latitude.
here is the code I am writing :
protected String currentLatitude, currentLongitude;
double lat, lon;
protected LocationManager locationManager;
private LocationListener ll;
locationManager = (LocationManager) getSystemService(
Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this,
"GPS enabled. Finding fine location. ",
Toast.LENGTH_SHORT).show();
ll = new GpsListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, ll);
} else {
if (locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Toast.makeText(this,
"GPS disabled. Finding coarse location.",
Toast.LENGTH_SHORT).show();
ll = new GpsListener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, ll);
} else {
Toast.makeText(this,
"Enable location settings to get current location.",
Toast.LENGTH_LONG).show();
}
}
private class GpsListener implements LocationListener {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
try {
Toast.makeText(getApplicationContext(), "Location Found",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
lat = location.getLatitude();
lon = location.getLongitude();
currentLatitude = Double.toString(lat);
currentLongitude = Double.toString(lon);
try {
if (ll != null)
locationManager.removeUpdates(ll);
} catch (Exception e) {
}
locationManager = null;
} else {
Toast.makeText(getApplicationContext(), "No Location Found",
Toast.LENGTH_LONG).show();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}// end of Class
I don't know how to get the city name from longitude,latitude.
I tried to do it but the address is NULL.
Upvotes: 1
Views: 759
Reputation: 798
This might be useful for you as it will return you the address fro latitude and longitude u provide to it..
Geocoder geocoder;
List<Address> addresses;
geocoder = new
Geocoder(this,
Locale.getDefault());
addresses =
geocoder.getFromLocation
(latitude,longitude, 1);
String address =addresses.get
(0).getAddressLine(0);
String city =addresses.
get(0). getAddressLine(1);
Upvotes: 0
Reputation: 2309
What you trying to do is called reverse geocoding. You can use Google's solution, which might not work on any device(Maybe this is your problem).
Or you can use really free and open source solutions like:
OpenStreetMap project: http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=-1.81602098644987&zoom=18&addressdetails=1
You can also use http://wikimapia.org/ API
Upvotes: 1