我正在编写此代码,以使用我的经度和纬度获取当前位置的城市名称。
这是我写的代码:
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
我不知道如何从经度,纬度获得城市名称。
我尝试这样做,但地址为NULL。
答案 0 :(得分:1)
您尝试做的是反向地理编码。 您可以使用Google的解决方案,这可能不适用于任何设备(也许这是您的问题)。
或者你可以使用真正免费和开源的解决方案,如:
OpenStreetMap项目: http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=-1.81602098644987&zoom=18&addressdetails=1
您还可以使用http://wikimapia.org/ API
答案 1 :(得分:0)
这可能对您有用,因为它会从您提供的纬度和经度返回地址..
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);