gpt4 book ai didi

javascript - GoogleMaps API 仅在开发工具打开时工作

转载 作者:行者123 更新时间:2023-11-28 17:59:02 25 4
gpt4 key购买 nike

嘿,我正在尝试在我的项目中添加 map 。我从 Google 获得了 GoogleMaps 的 API_KEY...我在控制台中没有错误,但 map 没有显示任何内容,直到我在 Google Chrome 上打开开发人员工具...

enter image description here 2

之后工作正常,但标记位于工作位置。控制台中仍然没有错误。

enter image description here

我做错了什么?

风格:

#map {
width: 100%;
height: 300px;
background-color: grey;
}

代码:

<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: -0.250608, lng: 52.025528};

var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});

var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Title!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap">
</script>

最佳答案

您正在一个不可见/没有尺寸的容器中初始化 map 。

打开开发工具会触发浏览器的大小调整,从而导致 map 自行调整大小。**

您可以通过以下任一方式修复它:

要么等待初始化 map ,直到它的容器可见

或调用 google.maps.event.trigger('resize',map) (其中 map 是 当您的容器变得可见时, map 的实例)。

** 证明这就是正在发生的事情:取消固定您的开发工具,使其成为 float 窗口。然后刷新页面(开发工具关闭)并在看不到 map 后再次打开开发工具,它仍然不可见,因为您的浏览器从未调整大小(因为您的开发工具是 float 的而不是停靠的)

关于javascript - GoogleMaps API 仅在开发工具打开时工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920593/

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