我使用地理编码 API 将地址转换为经度和纬度,然后使用接收到的坐标分配一个隐藏的输入值,而不是使用此数据在 map 上绘制。
我正在使用面向 javascript library 的客户端,这里是我的 javascript,稍作修改。
<script>
function initMap() {
var geocoder = new google.maps.Geocoder();
geocodeAddress(geocoder);
console.log('initMap');
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
console.log('geocodeAddresses');
geocoder.geocode({'address': address}, function(results, status) {
console.log('geocoder.geocode');
if (status === google.maps.GeocoderStatus.OK) {
console.log('status OK');
document.getElementById('lnglat').value = results[0].geometry.location;
console.log(results[0].geometry.location);
} else {
console.log('status error');
}
});
}
</script>
当我在 firebug 中看到输出时,我可以看到“initmap”、“geocodeAddresses”,但是在 geocoder.geocode 中什么也看不到。
我看不出任何原因,我在 firebug 中没有收到任何错误,所有必需的文件都在那里,我的 API key 也包含在内并且有效。
谢谢你的时间
编辑:似乎 geocoder.geocode 根本没有运行,当我在 geocodeAddress 末尾添加 console.log 时,它完全跳过了 geocoder.geocode。为什么会这样,因为 Firebug 中没有显示任何错误。
最佳答案
当您提交表单时,它将重新加载页面并且永远不会调用地理编码器函数。
添加action="javascript:void(0);"
在 <form>
阻止它重新加载页面和onclick
事件 <button>
调用您的地理编码器函数。
<body>
<form action="javascript:void(0);" id="search">
<input name="query" type="text" required/>
<input name="l" type="text" id="address" required/>
<input name="lnglat" type="text" id="lnglat" />
<button id="submit" onclick="query()" disabled="true">Submit</button>
</form>
</body>
关于javascript - geocoder.geocode() 未被执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37718074/