How to get Geocoder’s results on the LatLng’s country language?

廉价感情. 提交于 2019-12-23 02:09:19

问题


I use reverse geocoding in my app to transform LatLng objects to string addresses. I have to get its results not on device’s default language, but on the language of the country where given location is settled. Is there a way to do this? Here’s my code:


    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:


In your code, Geocoder returns address text in device locale(language).

1 From first element of "addresses" list, get Country Code.

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

Then returns Country Code (e.g. "MX")

2 Get Country Name.

   String langCode = null;

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

3 Instantiate Locale and Geocoder again, and request again.

    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;

This worked for me, hopefully for you too!



来源:https://stackoverflow.com/questions/31077014/how-to-get-geocoder-s-results-on-the-latlng-s-country-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!