我有下面的代码将 lat, long 转换为人类可读的地址。现在我有时间获取地址的完整详细信息,包括地址,城市,邮政编码,有时只获得"印度"等县名。如何根据纬度和经度获得准确的地址?请帮助我。
final List<Address> list = gCoder.getFromLocation(locationLatitude, locationLongitude, 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
StringBuilder sb = new StringBuilder();
if (address.getMaxAddressLineIndex() > 0) {
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
sb.append(address.getAddressLine(i)).append(",");
}
sb.append(address.getCountryName());
} else {
try {
sb.append(address.getAddressLine(0));
} catch (Exception ignored) {
}
}
strAddress = sb.toString();
strAddress = strAddress.replace(" ", "");
strAddress = strAddress.replace(",null", "");
strAddress = strAddress.replace("null", "");
strAddress = strAddress.replace("Unnamed", "");
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!TextUtils.isEmpty(strAddress)) {
tvLocation.setText(strAddress);
Log.e("Location", strAddress + "");
}else {
Snackbar.make(getView(), "Couldn't get the location. Make sure location is enabled on the device", Snackbar.LENGTH_SHORT)
.show();
}
}
});
从Geocoder
对象中,可以调用getFromLocation(double, double, int)
方法。
Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
}
else {
// do your stuff
}