我有一個腳本,我無法工作。我不斷收到錯誤'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>
使用傳遞給你的'errorFunction'的第二個參數來了解更多關於錯誤的信息。例如:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition –
嗨佩卡 - 感謝您的答覆,但我不知道如何實現這一點。 – Martyn