java Geocoder在Android中经常返回空值
我正在尝试将地理编码器值从MapFragment传递到LocationDetailsActivity
我得到了lat和lng的正确值,但当我尝试显示任何其他值时,大多数时候我得到的是空值,而不是城市和邮政编码(但不总是),而很多时候我得到的是正确的国家和州(也不总是)
映射片段代码:
// Set default latitude and longitude
double latitude = 15.4825766;
double longitude = -5.0076589;
// Get latitude and longitude of the current location and a LatLng object
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(LatLng arg0) {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> allAddresses = geocoder.getFromLocation(arg0.latitude, arg0.longitude, 1);
if (allAddresses.size() > 0 && allAddresses != null) {
Address address = allAddresses.get(0);
Intent intent = new Intent(getActivity(), LocationDetailsActivity.class);
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
intent.putExtra("city", allAddresses.get(0).getLocality());
intent.putExtra("zip", allAddresses.get(0).getPostalCode());
intent.putExtra("state", allAddresses.get(0).getAdminArea());
intent.putExtra("country", allAddresses.get(0).getCountryName());
startActivity(intent);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
位置详细信息活动代码:
Bundle bundle = getIntent().getExtras();
double lat = bundle.getDouble("latitude");
double lng = bundle.getDouble("longitude");
String city = intent.getStringExtra("city");
String zip = intent.getStringExtra("zip");
String state = intent.getStringExtra("state");
String country = intent.getStringExtra("country");
// I display my values here
mFirstValueDisplay.setText(String.valueOf(city));
mSecondValueDisplay.setText(String.valueOf(zip));
# 1 楼答案
根据我的经验,Android的地理编码api非常不可靠,我通常会在Url上向谷歌的地理编码Web服务发出请求:
"https://maps.googleapis.com/maps/api/geocode"
(如果您熟悉改装)latlng要反转地理编码的纬度和经度
语言地理编码响应的语言
密钥您的Api密钥
Go here for more info
# 2 楼答案
Geocoder通常会得到正确的值,但我通常会得到空值。根据@insomniac的建议,我修改了代码:
它仍然将某些区域显示为空。但这些都是较小的领域。希望有人觉得有用