【问题标题】:Get City Name From Location从位置获取城市名称
【发布时间】:2014-12-16 19:19:23
【问题描述】:

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

    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,因为位置未知..

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

【问题讨论】:

    标签: java android gps location city


    【解决方案1】:

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

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

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

    【讨论】:

    • 能否调试并查看其他值,例如 subLocality、subAdminArea 等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多