在 Google Maps API 中,我想在每次放置标记(标记都存储在数组中)时创建一个信息窗口。
声明信息窗口时:
var infowindow = new google.maps.InfoWindow();
我收到错误“google 未定义”。
如果我将这行代码移到创建标记的函数中,这只会停止,但是每次我放置一个标记时我都会创建变量 infowindow,我认为这是不好的做法?
我更愿意在我的 JS 开头声明 infowindow,然后每次放置标记时都使用它。
我在 SO 的其他答案中找不到任何有帮助的东西,我尝试重新排序 JS 文件,但到目前为止没有任何效果。
欢迎任何提示
最佳答案
这是因为 google maps 是异步加载的,您在 google maps API 加载之前调用了这一行。
这是等待加载的方法:
<!-- include this snippet anywhere -->
<script>
var infoWindow;
function initMap() {
infoWindow = new google.maps.InfoWindow();
}
</script>
<!-- include this script in your footer...or anywhere really -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
例如,如果您尝试执行以下操作:
<script>
var infoWindow = new google.maps.InfoWindow();
</script>
<script src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap" async defer></script>
然后你会得到一个错误,因为当 var infoWindow = ...
被执行时 google
不会被定义,因为 API 还没有加载。
您只能在执行回调(例如 initMap)后使用任何 google.maps.XXX
类
关于javascript - "Google is not defined"错误 - 尝试创建信息窗口谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44262112/