-->

Android reverse geocoding getLocality returns ofte

2020-05-31 05:18发布

问题:

I am using Android Geocoding to get the current city with Address.getLocality() method. It has worked fine, until just recently it appears to often return null for the locality. Here is an example:

    try {
        Geocoder c = new Geocoder(this, Locale.getDefault());
        double lat = 51.481;
        double lon = 0.0;
        List<Address> l = c.getFromLocation(lat, lon, 5);
        for (Address a: l) {
            Log.i("GeocoderTest", "Locality " + a.getLocality() + " (" + a + ")");
        }
    } catch (IOException e) {
        Log.e("GeocoderTest", "", e);
    }

This now logs the following message for the first returned address:

Locality null (Address[addressLines=[0:"14-18 Park Vista",1:"London Borough of Greenwich, London SE10",2:"UK"],feature=,admin=null,sub-admin=null,locality=null,thoroughfare=Park Vista,postalCode=null,countryCode=GB,countryName=United Kingdom,hasLatitude=true,latitude=51.4819069,hasLongitude=true,longitude=-6.327E-4,phone=null,url=null,extras=null])

Some locations do return the city in the locality, while a location next to it does not.

So it did work just fine before, actually I had not seen a null locality before. So I guess something must have changed in Google's geocoding service. Any idea what is going on, and is this situation permanent? If yes, what would be the best way to determine the city from a location?

回答1:

I noticed, that very often getLocality() returns null for the first address in the list, returned by Geocoder.
On the other hand correct city name stays at Locality of a next Address.
So I am using this workaround and it works well for big cities:

 private String getCityNameByCoordinates(double lat, double lon) throws IOException {
    List<Address> addresses = mGeocoder.getFromLocation(lat, lon, 10);
    if (addresses != null && addresses.size() > 0) {
        for (Address adr : addresses) {
            if (adr.getLocality() != null && adr.getLocality().length() > 0) {
                return adr.getLocality();
            }
        }
    }
    return null;
}


回答2:

Now I live in Canada, Ontario, Hamilton (Hamilton is my city, Ontario is the province)

I noticed that getLocality() returns null, and getAdminArea() returns Ontario, and getSubLocality() returns Hamilton. ch