如何使用纬度和经度获取棒棒糖及以上地址?

时间:2017-01-25 10:44:24

标签: android google-maps android-studio

我正与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();
 }
}

1 个答案:

答案 0 :(得分: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