2015-06-26 52 views
1

我在我的應用中使用反向地理編碼將LatLng對象轉換爲字符串地址。我必須得到它的結果,而不是使用設備的默認語言,而是取決於給定位置所在國家/地區的語言。有沒有辦法做到這一點? 這裏是我的代碼:如何使用LatLng的國家語言獲取Geocoder的結果?

 

    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; 

+0

你是說如果設備是英文的,而你在看北京,它實際上應該會返回普通話字符? –

+0

@TeoInke不知道國語字符,我的意思是它應該返回法國的名字,德國的德語,意大利的意大利語等。 – user2806449

+0

好的,明白了。從我發現可以在JS API上設置語言,但不在Android上。 –

回答

2

在代碼中,地理編碼器返回的設備環境(語言)地址文本。

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; 

這對我有用,希望對您也有幫助!

+0

謝謝你,也爲我工作,除非我不創建新的語言環境並使用第2步中的對象。 – user2806449

相關問題