2017-01-25 32 views
1

我與Geocoder工作使用latitudelongitude找到一個位置的確切地址,但它並沒有在lollipop支持及以上如何使用經緯度獲得棒棒糖及以上的地址位置?

Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault()); 
String mylocation; 
if (Geocoder.isPresent()) { 
try { 
    List <Address> addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
    if (addresses != null && addresses.size() > 0) { 
    Address address = addresses.get(0); 
    String addressText = String.format("%s, %s, %s", 
    // If there's a street address, add it 
    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", 
    // Locality is usually a city 
    address.getLocality(), 
    // The country of the address 
    address.getCountryName()); 
    mylocation = "Lattitude: " + location.getLatitude() + " Longitude: " + location.getLongitude() + "\nAddress: " + addressText; 
    address1.setText(addressText); 
    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
} 
+0

到目前爲止,您嘗試了什麼?是否有任何錯誤消息或代碼可以共享? – hering

回答

3

您可以使用下面的代碼地址:

//Set Address 
try { 
    List <Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
    if (addresses != null && addresses.size() > 0) { 
    String address = addresses.get(0).getAddressLine(0) + " " + addresses.get(0).getAddressLine(1); 
    if (address != null) { 
    textViewAddress.setText(address); 
    } else { 
    textViewAddress.setText("Not Available"); 
    } 

    String city = addresses.get(0).getAddressLine(2); 
    if (city != null) { 
    textViewCity.setText(city); 
    } else { 
    textViewCity.setText("Not Available"); 
    } 

    String state = addresses.get(0).getAdminArea(); 
    if (state != null) { 
    textViewState.setText(state); 
    } else { 
    textViewState.setText("Not Available"); 
    } 

    String country = addresses.get(0).getCountryName(); 
    if (country != null) { 
    textViewCountry.setText(country); 
    } else { 
    textViewCountry.setText("Not Available"); 
    } 

    System.out.println("Address >> " + address + " " + " \n" + state + " \n" + country); 

    } 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

或者

String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex() 
String city = addresses.get(0).getLocality(); 
String state = addresses.get(0).getAdminArea(); 
String country = addresses.get(0).getCountryName(); 
String postalCode = addresses.get(0).getPostalCode(); 
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL 

參考以下鏈接:Get Address

+0

我試過了,兩者都不適用棒棒糖及以上版本。有沒有其他方法。請幫助 – Jincy

+0

@Jincy:我已經在我的項目中運行了您的代碼,並在我的marshmallo設備上正常工作。我得到我的經緯度和地址正確。 你能否定義你的實際問題? – BK19

+0

是這個程序需要的google api密鑰 – Jincy