0
我正在做一個應用程序,我必須顯示當前位置的名稱。我獲得了經度和緯度,但無法獲取位置的名稱。爲什麼我不能檢索當前位置的名稱?
我試圖做到這一點的代碼是:
context = getApplicationContext();
Location location;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
double lon, lat;
try
{
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lon = location.getLongitude();
lat = location.getLatitude();
Toast.makeText(context, "Lat: "+lat+"\nLon: "+lon, Toast.LENGTH_LONG).show();
List<Address> mAddresses = null;
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
mAddresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
@SuppressWarnings("unchecked")
String cityName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0)
.getLocality() : TimeZone.getDefault().getID();
@SuppressWarnings("unchecked")
String countryName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0)
.getCountryName() : Locale.getDefault().getDisplayCountry()
.toString();
try
{
lm.clearTestProviderLocation(LocationManager.GPS_PROVIDER);
}
catch(Exception e)
{}
Toast.makeText(context, "Using GPS Provider", Toast.LENGTH_SHORT).show(); }
catch(Exception exp1){
try
{
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lon= location.getLongitude();
lat = location.getLatitude();
Toast.makeText(context, "Lat: "+lat+"\nLon: "+lon, Toast.LENGTH_LONG).show();
List<Address> mAddresses = null;
Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
mAddresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
@SuppressWarnings("unchecked")
String cityName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0).getLocality() : TimeZone.getDefault().getID();
@SuppressWarnings("unchecked")
String countryName = (mAddresses != null) ? ((List<Address>) mAddresses).get(0).getCountryName() : Locale.getDefault().getDisplayCountry().toString();
try
{
lm.clearTestProviderLocation(LocationManager.NETWORK_PROVIDER);
}
catch(Exception e)
{}
Toast.makeText(context, "Using Network Provider", Toast.LENGTH_SHORT).show();
}
你是否得到像.. Geocoder:服務不可用? – 2013-05-07 06:41:08