首页 文章

如何在LatLng的国家语言中获得Geocoder的结果?

提问于
浏览
1

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

  • 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;
    

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

相关问题