反向地理编码以显示地址

时间:2017-01-06 20:30:19

标签: javascript google-maps geocode

我有一个我无法工作的脚本。我一直收到错误'Geocoder failed'但我不确定为什么。它应该得到long / lat然后反向地理编码它以在警告框中显示街道地址。我已经尝试确保浏览器让它共享该位置。我也尝试过通过HTTPS访问,因为我读到现在需要它,但它仍然无效。 如果有人能帮助我完成这项工作,我将非常感激! 提前谢谢。

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Current Location Address</title>
    <style>
    </style>
</head>



<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
  var geocoder;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get the latitude and the longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    codeLatLng(lat, lng)
}

function errorFunction(){
    alert("Geocoder failed");
}

  function initialize() {
    geocoder = new google.maps.Geocoder();



  }

  function codeLatLng(lat, lng) {

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
      console.log(results)
        if (results[1]) {
         //formatted address
         alert(results[0].formatted_address)
        //find country name
             for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_components[i];
                    break;
                }
            }
        }
        //city data

        alert(city.short_name + " " + city.long_name)


        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script> 
</head> 
<body onload="initialize()"> <font face="verdana">
        <!DOCTYPE html> 
If available, your current address will have been displayed in a message window. Please press 'Back' when finished.


</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的errorFunction会自动传递error参数,您可以查看该参数:

function errorFunction(error){
    alert("Geocoder failed: "+error.message);
}

有关更多背景和示例,请参阅the MDN docs