我可以在ActivityMaps.java文件中实现反向地理编码功能吗?

时间:2015-05-29 14:12:20

标签: java android google-maps geocoding reverse-geocoding

我目前正在Android Studio 1.1.0中开发应用程序,我已经实现了Google Maps API,我可以从中检索用户的当前位置,但我想将其转换为地址。我可以在MapsActivity.java文件中使用以下代码吗?

function getReverseGeocodingData(lat, lng) {

   var latlng = new google.maps.LatLng(lat, lng);
   // This is making the Geocode request
   var geocoder = new google.maps.Geocoder();
   geocoder.geocode({ 'latLng': latlng }, function (results, status) {
      if (status !== google.maps.GeocoderStatus.OK) {
        alert(status);
        }

    // This is checking to see if the Geoeode Status is OK before proceeding
        if (status == google.maps.GeocoderStatus.OK) {
        console.log(results);

        var address = (results[0].formatted_address);
    }
});

}

任何帮助将不胜感激。 Android Studio仍然相对较新

1 个答案:

答案 0 :(得分:1)

您可以使用 android.location.Geocoder 轻松完成此操作。

 // get current locality based on lat lng
    Geocoder geocoder;
    List<Address> addresses;
    geocoder = new Geocoder(this, Locale.getDefault());
    addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

    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();

要获得良好的练习,请确保在AsyncTask中执行此操作。