我正在尝试使用Geocoding从Latitude和Longitude获取postalCode,但它总是返回NULL,有没有办法让它自由或者我用Geocode做错了?
这是代码::
Geocoder geo = new Geocoder(context,
Locale.getDefault());
List<Address> add;
try {
Double mLattitude = Double.parseDouble(mLatt);
Double mLongitude = Double.parseDouble(mLong);
add = geo.getFromLocation(mLattitude, mLongitude, 1);
if (add != null && !add.isEmpty()) {
int size = add.size();
Log.e(" init Geo "," List address size "+size);
Log.e(" initGeo ","Add json "+add);
StringBuilder str = new StringBuilder();
if (geo.isPresent()) {
Address returnAddress = add.get(0);
if(returnAddress!=null) {
String zipcode = returnAddress.getPostalCode();
str.append(zipcode + "");
}else
{
return thirdPartyService();
}
if (str == null || str.toString().isEmpty() || str.toString().equalsIgnoreCase("null")) {
return thirdPartyService();
}
else
{
Log.e(" ", "GEO CODE PRESENT");
return str.toString();
}
} else {
Log.e(" ", "GEO CODE NOT PRESENT");
return thirdPartyService();
}
}else
{
Log.e(" ", "GEO CODE NOT PRESENT");
return thirdPartyService();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
09-08 11:37:42.044 32723-640/? E/init Geo﹕ List address size 1
09-08 11:37:42.044 32723-640/? E/initGeo﹕ Add json [Address[addressLines=[0:"93, Delhi - Jaipur Expy",1:"Sector 32",2:"Gurgaon, Haryana 122001",3:"India"],feature=93,admin=Haryana,sub-admin=null,locality=Gurgaon,thoroughfare=Delhi - Jaipur Expy,postalCode=null,countryCode=IN,countryName=India,hasLatitude=true,latitude=28.448048,hasLongitude=true,longitude=77.040622,phone=null,url=null,extras=null]]
答案 0 :(得分:1)
根据Android documentation,如果未知,地理编码会返回address or null
的邮政编码。
您的代码实现是正确的。
当我用(37.22,33.22)测试时,它返回null。
但是当我使用(28.6100,77.2300)时它返回110001
所以你在应用程序中显示时进行了一些检查
答案 1 :(得分:0)
尝试以下代码。
private void getLocationAddress(final double latitude, final double longitude){
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocation(
latitude, longitude, 1);
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
result = sb.toString();
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
}
也使用以下权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
答案 2 :(得分:0)
邮政编码总是使用地理编码时为空,它取决于位置。尝试在城市的一些地方,你可能会得到它,并在农村得到它是有问题的。因此,如果您的应用需要它,请尽可能使用null
值