从位置获取城市名称

时间:2014-12-16 19:19:23

标签: java android gps location city

我有一个应用程序可以获取位置并获取用户城市的天气..天气是从城市名称(应该是具体的)获得的。我使用以下代码获取位置:

    LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener locLis = new MyLocationListener();
    locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            locLis);
    Location location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    response.setText("Last Known Location Is " + location);
    try {

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();


        Geocoder geocoder = new Geocoder(MainActivity.this,Locale.getDefault());
        List<Address> addresses = geocoder.getFromLocation(latitude,longitude, 1);

        address = addresses.get(0).getAddressLine(0);
        city = addresses.get(0).getAddressLine(1);
        country = addresses.get(0).getCountryName();

        String text = "Location from Last: " + address + " ," + city + " ," + country;

        response.setText(text);

    } catch (Exception e) {
        response.setText("Location Exception : " + e);
    }

返回&#34; Tanta,Qesm 2&#34;我只想要&#34; Tanta&#34;,我也尝试使用addresses.get(0).getLocality()但它返回null因为locality未知..

那么,任何想法? :)

1 个答案:

答案 0 :(得分:0)

addresses.get(0).getLocality()应该返回locality。它为“Tanta,Qesm 2”返回null表示此特定位置没有可用的位置。

您还可以尝试迭代地址列表并查看是否存在位置。

for(Address a: addresses){
   if(a.getLocality != null){
      // take this one
   }
}
相关问题