从经度,纬度获取邮政编码 - android - Java

时间:2014-10-04 19:44:31

标签: java android google-maps reverse-geocoding

我已经在SO上尝试了几种可能的“解决方案”,但对我来说没有任何作用。基本上,我试图从lat / lng获取邮政编码。我读到Geocoder和模拟器Genymotion存在一些问题,但我不确定,如果确实存在这个问题。此外,我还试图通过HTTP Request获取邮政编码作为JSON对象,但这也没有用。

这是我的代码:

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

问题是,addr.size()为0,我不知道为什么。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

我对Geocoder对象一无所知,但我个人会使用Google Geocoding Api。

通过简单的GET,您就可以获得所需的信息。

点击here获取官方文档。

答案 1 :(得分:0)

之前我遇到过这样的问题,但是由于你没有发布你的logcat,所以不知道你的问题是否相同。如果您的logcat中出现“服务不可用”错误,则Geocoder存在错误。 https://stackoverflow.com/a/4045287/687245。如果是这样,有人通过GET调用Geocode提供了解决方法。

这是我从Geocode获取经度和经度的解决方法。其他人在Stackoverflow上发布了这个代码,所有的功劳都给了他。您所要做的就是将其更改为通过纬度和经度查询而不是字符串查询,并检索邮政编码而不是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();
}
相关问题