我正在尝试获取邮政编码,但我无法获得邮政编码(邮政编码)。我能够获得当前的城市,但当我尝试获取zipcode时,它给了我一个空指针异常。 任何人都可以帮助我。
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
答案 0 :(得分:6)
我使用google webservice来获取邮政编码。
以下是Google网络服务
http://maps.googleapis.com/maps/api/geocode/json?latlng=lattitude,longitude&sensor=true
这里的经度和经度。所以要替换这些值,你就会收到回复并解析它们并得到邮政编码。
答案 1 :(得分:6)
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;
}
}
答案 2 :(得分:4)
尝试使用Android内置Geocoder来获取纬度和经度的详细信息,而无需调用google location api,如下所示:
使用Gecoder
初始化Context
:
final Geocoder gcd = new Geocoder(context);
从Lat-Long,Here(10)max result中获取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;
}
}
答案 3 :(得分: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;
}