简体   繁体   中英

Get zip code from longitude, latitude - android - Java

I already tried several possible "solutions" here on SO, but nothing worked for me. Basically, I am trying to get the zip code from lat/lng. I read that there are some issues with Geocoder and the emulator Genymotion, but I am not sure, if that really is the problem. Furthermore, I also tried to get the zip code via HTTP Request as a JSON object, but this also didn't work.

Here is my code:

@Override
    public void onLocationChanged(Location location) {

        EditText zipCode = (EditText) findViewById(R.id.zip_code);

        zipCode.setText(getZipCodeFromLocation(location));

    }

    private String getZipCodeFromLocation(Location location) {
        Address addr = getAddressFromLocation(location);
        return addr.getPostalCode() == null ? "" : addr.getPostalCode();
    }

    private Address getAddressFromLocation(Location location) {
        Geocoder geocoder = new Geocoder(this);
        Address address = new Address(Locale.getDefault());
        try {
            List<Address> addr = geocoder.getFromLocation(
                    location.getLatitude(), location.getLongitude(), 1);
            if (addr.size() > 0) {
                address = addr.get(0);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return address;
    }

The problem is, that addr.size() is 0 and I don't know why.

Any help would be greatly appreciated.

I don't have any knowledge about the Geocoder object but personally I would use the Google Geocoding Api.

With a simple GET you're able to get your desired information.

Click here for the official documentation.

I've had an issue like this before, but don't know if it's the same to yours since you didn't post your logcat. If you're getting a "Service not available" error in your logcat there is a bug with Geocoder. https://stackoverflow.com/a/4045287/687245 . If so someone has provided a work around to query it via a GET call to Geocode.

This is a workaround for me to get latitude and longitude from Geocode. Someone else posted this code on Stackoverflow, and all credit is given to him. All you have to do is change it to query via latitude and longitude instead of a string query and retrieve the postal code instead of lat lng.

public void updateLocationByQuery(final String query) {
    if (mRunning)
        return;

    new AsyncTask<Void, Void, LatLng>() {
        protected void onPreExecute() {
            mRunning = true;
        };

        @Override
        protected LatLng doInBackground(Void... params) {
            LatLng p = null;

            Geocoder geoCoder = new Geocoder(getActivity(),
                    Locale.getDefault());
            try {
                List<Address> addresses = geoCoder.getFromLocationName(
                        query, 1);
                if (addresses.size() > 0) {
                    p = new LatLng(addresses.get(0).getLatitude(),
                            addresses.get(0).getLongitude());
                } else {
                    Toast.makeText(getActivity(),
                            "Unable to find location by query: " + query,
                            Toast.LENGTH_LONG).show();
                }
            } catch (Exception ignored) {
                // after a while, Geocoder start to trhow
                // "Service not availalbe" exception. really weird since it
                // was working before (same device, same Android version
                // etc..
                ignored.printStackTrace();
            }

            if (p != null) // i.e., Geocoder succeed
            {
                return p;
            } else // i.e., Geocoder failed
            {
                return fetchLocUsingGoogleMap(query);
            }
        }

        // Geocoder failed :-(
        // Our B Plan : Google Map
        private LatLng fetchLocUsingGoogleMap(String query) {
            double lng = 0, lat = 0;
            query = query.replace("\n", " ").replace(" ", "%20");
            String googleMapUrl = "http://maps.google.com/maps/api/geocode/json?address="
                    + query + "&ka&sensor=false";
            try {
                JSONObject googleMapResponse = new JSONObject(
                        ANDROID_HTTP_CLIENT.execute(new HttpGet(
                                googleMapUrl), new BasicResponseHandler()));

                lng = ((JSONArray) googleMapResponse.get("results"))
                        .getJSONObject(0).getJSONObject("geometry")
                        .getJSONObject("location").getDouble("lng");

                lat = ((JSONArray) googleMapResponse.get("results"))
                        .getJSONObject(0).getJSONObject("geometry")
                        .getJSONObject("location").getDouble("lat");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return new LatLng(lat, lng);
        }

        @Override
        protected void onPostExecute(LatLng loc) {
            mRunning = false;
            if (loc != null) {
                moveCamera(loc);
            }
        };
    }.execute();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM