5

我正在尝试获取邮政编码,但无法获取邮政编码(邮政编码)。我可以获取当前城市,但是当我尝试获取邮政编码时,它给了我一个空指针异常。谁能帮我。

final Geocoder gcd = new Geocoder(getApplicationContext(),
                Locale.getDefault());

List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0)                                   Log.d(addresses.get(0).getLocality()); // I can get city name here.
Log.d(addresses.get(0).getPostalCode();// here i am getting nullpoiter exception
4

4 回答 4

8

尝试使用android内置的地理编码器从纬度和经度获取详细信息,而无需调用谷歌位置api,如下所示:

Gecoder使用初始化Context

final Geocoder gcd = new Geocoder(context);

从 Lat-Long,Here (10) 最大结果中获取Address结果。

List<Address> addresses = gcd.getFromLocation(latitude, longitude, 10);

迭代以获取所需的位置详细信息:

for (Address address : addresses) {
    if(address.getLocality()!=null && address.getPostalCode()!=null){
        Log.d(address.getLocality());
        Log.d(address.getPostalCode();
       break;
    }
}
于 2013-09-02T08:39:56.717 回答
7
    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
    List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
    Address address=null;
    String addr="";
    String zipcode="";
    String city="";
    String state="";
    if (addresses != null && addresses.size() > 0){

            addr=addresses.get(0).getAddressLine(0)+"," +addresses.get(0).getSubAdminArea();
                 city=addresses.get(0).getLocality();
                 state=addresses.get(0).getAdminArea();

                 for(int i=0 ;i<addresses.size();i++){
                     address = addresses.get(i);
                     if(address.getPostalCode()!=null){
                         zipcode=address.getPostalCode();
                         break;
                     }

                }
于 2014-04-10T15:56:35.333 回答
6

我使用谷歌网络服务来获取邮政编码。

以下是谷歌网络服务

http://maps.googleapis.com/maps/api/geocode/json?latlng=lattitude,longitude&sensor=true

这里的纬度和经度。所以替换这些值,您将得到响应并解析它们并获取邮政编码。

于 2013-09-13T07:37:33.450 回答
1

我有实用方法来获取非常整洁且工作正常的邮政编码..

public static String getPostalCodeByCoordinates(Context context, double lat, double lon) throws IOException {

    Geocoder mGeocoder = new Geocoder(context, Locale.getDefault());
    String zipcode=null;
    Address address=null;

    if (mGeocoder != null) {

        List<Address> addresses = mGeocoder.getFromLocation(lat, lon, 5);

        if (addresses != null && addresses.size() > 0) {

            for (int i = 0; i < addresses.size(); i++) {
                address = addresses.get(i);
                if (address.getPostalCode() != null) {
                    zipcode = address.getPostalCode();
                    Log.d(TAG, "Postal code: " + address.getPostalCode());
                    break;
                }

            }
            return zipcode;
        }
    }

    return null;
}
于 2018-04-03T10:56:51.360 回答