【发布时间】:2019-09-23 16:05:55
【问题描述】:
我有一个附近的搜索地图,每次打开这个地图页面,它都会返回当前位置,现在当我通过坐标获取当前位置时,我想将其反向地理编码为地址名称,问题是我修改了我的代码来自这个来源:https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse
与
<script>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
document.getElementById("address").value=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',');
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
这应该返回地图中的地名,就像我从上面复制的源代码一样 https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse,我的修改可能有什么问题?运行修改后的代码时,控制台出现错误error in the console
这是我没有 api 密钥的完整代码:https://pastebin.com/BhEqRsq0
【问题讨论】:
-
如何包含 API?
document.getElementById('curr').value;是否包含字符串(您的代码假定它是逗号分隔的字符串)。请提供一个 minimal reproducible example 来证明您的问题。 -
document.getElementById('curr').value 是一个带逗号的字符串
-
只有在地理位置功能成功检索到位置之后。
-
这是什么意思?
标签: javascript google-maps reverse-geocoding