2017-01-06 132 views
-1

我有一个脚本,我无法工作。我不断收到错误'Geocoder失败',但我不知道为什么。它应该得到长/纬度,然后反向地理编码它显示在一个警告框中的街道地址。我曾尝试确保浏览器让它共享位置。我也尝试通过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> 
+0

使用传递给你的'errorFunction'的第二个参数来了解更多关于错误的信息。例如:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition –

+0

嗨佩卡 - 感谢您的答复,但我不知道如何实现这一点。 – Martyn

回答

0

errorFunction自动传递的error参数,你可以在一起来看看:

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

the MDN docs更多的背景和例子。

+0

谢谢你,我将它添加到我的脚本中,但是当我运行它时,我只是得到'Geocoder失败:'显示在警告框中。它似乎没有显示任何细节。 – Martyn

+0

嗯,奇怪。用'error.code'切换'error.message'会不会改变? –

+0

这确实改变了它,是的。现在我得到'Geocoder失败:2',但我不确定2是指什么。 – Martyn