javascript - ReferenceError:谷歌未定义/地理编码API
问题描述
我试图创建地理编码功能(地理编码API),它不断返回google is not defined
,我已经根据这个答案更改了链接,但它没有用:(它在geocoder = new google.maps.Geocoder();
JS:
geocoder = new google.maps.Geocoder();
function address() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
for (i = 0; i < index.length; i++) {
var address = index[i].Origin;
console.log(address)
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
关联:
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCNpeRgwCQoHIlLn-X8TIB9SnO8iLPt808&callback=initMap"
async defer></script>
抱歉,如果问题重复,我几乎尝试了所有东西(也在堆栈之外),是的,没有任何变化。
解决方案
将任何依赖于 API 的代码(以 开头google.maps.
)放在initMap
函数中或同步加载 API(从脚本 URL中删除async defer
和)&callback=initMap
推荐阅读
- android - 为什么我无法在 Flutter 中获取已安装的 Android 应用列表?
- regex - 删除带有特定文本或单词的行尾 - 在 Perl 脚本中
- laravel - 在 Laravel Livewire 中使用外键从另一个表中获取特定数据
- ios - 如何录制 ARKit 场景但排除 UI 元素?
- git - 用于添加单元测试的语义提交消息类型
- python - 如何在 sqlite3 python 中从数据库中打印唯一数据?
- javascript - 用 fetch 替换短 XMLHpptRequest
- java - 在 Spring MVC 中获取 HttpServletRequest?
- apache-kafka - Kafka-生产者重复检查
- java - Java Async 不适用于轮询循环