1

我有一个应用程序可以获取位置并获取用户所在城市的天气。天气是从城市名称中获取的(应该是特定的)。我使用以下代码获取位置:

    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);
    }

返回“Tanta,Qesm 2”我只想要“Tanta”,我也尝试使用addresses.get(0).getLocality()但它返回null,因为位置未知..

那么,有什么想法吗?:)

4

1 回答 1

0

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

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

for(Address a: addresses){
   if(a.getLocality != null){
      // take this one
   }
}
于 2014-12-16T19:36:20.623 回答