【发布时间】:2017-01-06 20:30:18
【问题描述】:
我有一个无法运行的脚本。我不断收到错误“地理编码器失败”,但我不知道为什么。它应该获取长/纬度,然后对其进行反向地理编码以在警报框中显示街道地址。我已尝试确保浏览器允许它共享位置。我也尝试过通过 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>
【问题讨论】:
-
使用传递给
errorFunction的第二个参数来了解有关错误的更多信息。示例:developer.mozilla.org/en-US/docs/Web/API/Geolocation/… -
嗨 Pekka - 感谢您的回复,但我不知道如何实施。
标签: javascript google-maps geocode