如何使用LatLng的国家语言获得Geocoder的结果?

时间:2015-06-26 15:30:16

标签: java android locale reverse-geocoding

我在我的应用中使用反向地理编码将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;

1 个答案:

答案 0 :(得分:2)

在您的代码中,Geocoder以设备区域设置(语言)返回地址文本。

1从“地址”列表的第一个元素,获取国家代码。

    Address address = addresses.get(0);
    String countryCode = address.getCountryCode

然后返回国家代码(例如“MX”)

2获取国家/地区名称。

   String langCode = null;

   Locale[] locales = Locale.getAvailableLocales();
   for (Locale localeIn : locales) {
          if (countryCode.equalsIgnoreCase(localeIn.getCountry())) {
                langCode = localeIn.getLanguage();
                break;
          }
    }

3再次实例化区域设置和地理编码,然后再次请求。

    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;

这对我有用,希望对你也有用!

相关问题