我正在创建一个项目,我需要找到用户的位置并显示附近的地方,如医院,餐厅等。我正在使用地理编码API测试此模块,我正在使用反向地理 - 编码从纬度和经度获得人类可读的形式。我也使用Axois来解析json对象。这是我的代码:
<script>
// if user click allow location (get the latitude and longitude from the gps)
document.getElementById('alow').onclick = function() {
var startPos;
var lat ;
var lon;
var geoSuccess = function(position) {
// Do magic with location
startPos = position;
document.getElementById('startLat').innerHTML = 'latitude, longitude:';
document.getElementById('startLon').innerHTML = startPos.coords.latitude.toFixed(6) + ", " + startPos.coords.longitude.toFixed(6);
reverserGeocode(startPos.coords.latitude.toFixed(6), startPos.coords.longitude.toFixed(6));
};
var geoError = function(error) {
switch (error.code) {
case error.UNKOWN_ERROR:
console.log("Unknown error!");
break;
case error.PERMISSION_DENIED:
console.log("Permission denied!");
break;
case error.POSITION_UNAVAILABLE:
console.log("Position Unavailable!");
break;
case error.TIMEOUT:
console.log("Timeout!");
break;
}
};
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
};
// if user enters location itself, get the location (City/State)
document.getElementById('go').onclick = function() {
var location = document.getElementById('location').value;
geocode(location);
};
function reverserGeocode(lat, lon) {
axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
params: {
latlng:lat+','+lon,
key:'My_Api_key_here'
}
})
.then(function (response) {
console.log(response);
// format address
if(response.data.results.length > 0) {
var formatedAddress = response.data.results[0].formatted_address;
document.getElementById('formattedAddress').innerHTML = formattedAddress;
}else {
console.log("From else statement: No address found at: " + lat + ", " + lon);
}
})
.catch(function (error) {
console.log(error);
});
}
</script>
这是控制台的结果:
{
"results" : [],
"status" : "ZERO_RESULTS"
}
当我写镇/城市名称时,它会返回正确的json对象。我在谷歌地图中粘贴了纬度和经度来获取位置,但它显示“ZERO_RESULTS”。 感谢。