如何在 LatLng 的国家语言上获得 Geocoder 的结果?
How to get Geocoder’s results on the LatLng’s country language?
我在我的应用程序中使用反向地理编码将 LatLng 对象转换为字符串地址。我必须得到的结果不是设备的默认语言,而是给定位置所在国家/地区的语言。有没有办法做到这一点?
这是我的代码:
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List addresses;
try {
addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1);
}
catch (IOException | IndexOutOfBoundsException | NullPointerException ex) {
addresses = null;
}
return addresses;
在您的代码中,Geocoder returns 以设备区域设置(语言)处理文本。
1 从 "addresses" 列表的第一个元素中获取国家代码。
Address address = addresses.get(0);
String countryCode = address.getCountryCode
然后 returns 国家代码(例如 "MX")
2 获取国家名称。
String langCode = null;
Locale[] locales = Locale.getAvailableLocales();
for (Locale localeIn : locales) {
if (countryCode.equalsIgnoreCase(localeIn.getCountry())) {
langCode = localeIn.getLanguage();
break;
}
}
3 再次实例化 Locale 和 Geocoder,再次请求。
Locale locale = new Locale(langCode, countryCode);
geocoder = new Geocoder(this, locale);
List addresses;
try {
addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1);
}
catch (IOException | IndexOutOfBoundsException | NullPointerException ex) {
addresses = null;
}
return addresses;
这对我有用,希望对你也有用!
我在我的应用程序中使用反向地理编码将 LatLng 对象转换为字符串地址。我必须得到的结果不是设备的默认语言,而是给定位置所在国家/地区的语言。有没有办法做到这一点? 这是我的代码:
Geocoder geocoder = new Geocoder(context, Locale.getDefault()); List addresses; try { addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1); } catch (IOException | IndexOutOfBoundsException | NullPointerException ex) { addresses = null; } return addresses;
在您的代码中,Geocoder returns 以设备区域设置(语言)处理文本。
1 从 "addresses" 列表的第一个元素中获取国家代码。
Address address = addresses.get(0);
String countryCode = address.getCountryCode
然后 returns 国家代码(例如 "MX")
2 获取国家名称。
String langCode = null;
Locale[] locales = Locale.getAvailableLocales();
for (Locale localeIn : locales) {
if (countryCode.equalsIgnoreCase(localeIn.getCountry())) {
langCode = localeIn.getLanguage();
break;
}
}
3 再次实例化 Locale 和 Geocoder,再次请求。
Locale locale = new Locale(langCode, countryCode);
geocoder = new Geocoder(this, locale);
List addresses;
try {
addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1);
}
catch (IOException | IndexOutOfBoundsException | NullPointerException ex) {
addresses = null;
}
return addresses;
这对我有用,希望对你也有用!