gpt4 book ai didi

javascript - 如何在加载 google.maps.OverlayView 派生类之前等到 google maps API 加载完毕

转载 作者:数据小太阳 更新时间:2023-10-29 05:22:11 25 4
gpt4 key购买 nike

我有一个单独的 label.js 文件,我在其中定义了一个自定义叠加层。它使用 google.maps.OverlayView 作为其原型(prototype):

Label.prototype = new google.maps.OverlayView();

我不确定将此 js 文件的脚本标记放在我的 index.html 文件中的什么位置。如果我将脚本标签放在谷歌地图加载标签下面,如下所示:

....
<script async defer
src="https://maps.googleapis.com/maps/api/js?...
</script>
<script src="js/label.js"></script>
</body>
</html>

label.js 文件立即加载,而 map api 尚未加载导致错误。

我目前通过在我的 map 加载回调中手动加载 JS 来解决这个问题:

function initMap() {
gMap = new google.maps.Map(document.getElementById(strMapDivName), {
center: {lat: 21, lng: 78},
mapTypeId: google.maps.MapTypeId.HYBRID,
zoom: 6,
heading: 90,
tilt: 0
});

// Load label.js afterwards so we can be sure that the google maps api has loaded
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "js/label.js")

document.getElementsByTagName("head")[0].appendChild(fileref)

}

这是解决这个问题的最佳方法吗?

最佳答案

您应该在 API 调用中包含一个回调函数。

<script async defer src="https://maps.googleapis.com/maps/api/js?callback=myFunction"></script>

然后您可以在回调函数中包含任何与 map 相关的代码:

function myFunction() {
// Your code here
}

如果您需要等到 map “就绪”,即 map 显示时带有 map 选项和“空闲”,您可以使用:

google.maps.event.addListenerOnce(map, 'idle', function () {
// map is ready
});

但您仍应将其包含在回调函数中。

关于javascript - 如何在加载 google.maps.OverlayView 派生类之前等到 google maps API 加载完毕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32808613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com