简体   繁体   English

Google地图Javascript API仅在控制台处于打开状态时加载数据

[英]Google Maps Javascript API only loads data, when console is open

I am trying to display a map on my page, which sets a marker. 我正在尝试在我的页面上显示一个地图,该地图设置了一个标记。

What's my problem 我的问题是什么?

The map instance works without any problems. 地图实例没有任何问题。 There is no error in the console or from Google at self. 控制台或谷歌自己都没有错误。 But unfortunately, the map data is not loading. 但遗憾的是,地图数据未加载。 I just get the Google logo and a grey background, as you can see on the picture. 我只是得到了Google徽标和灰色背景,如图所示。 来自Google Maps API的灰色地图

Then, when I open the console of Google Chrome, it loads the map data and it display me the map with the requested map type. 然后,当我打开谷歌浏览器的控制台时,它会加载地图数据,并显示包含所请求地图类型的地图。

打开开发人员控制台后加载的数据

What I tried 我尝试了什么

I searched in the internet, found some other problems like the grey box, but the solution doesn't help me. 我在互联网上搜索,发现了一些其他问题,如灰盒子,但解决方案对我没有帮助。

Right now my code looks like this: 现在我的代码看起来像这样:

<div id="map" style="width:100%;height:400px;"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap"></script>
<script>
function initMap() {
   //Just some example coordinates
   var lat = 47.8;
   var lon = 8.9
   var location = {lat: lat, lng: lon};
   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: location,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   });
   var marker = new google.maps.Marker({
      position: location,
      map: map
   });
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>

Can someone help me? 有人能帮我吗?

It's not perfect but you can try to force the resize when the maps is loaded : 它并不完美,但您可以尝试在加载地图时强制调整大小:

google.maps.event.addListenerOnce(map, 'idle', function(){
    $(window).trigger('resize'); 
});

Or without jQuery: 或者没有jQuery:

google.maps.event.addListenerOnce(map, 'idle', () => {
    const event = new Event('resize');
    window.dispatchEvent(event);
});

You Shouldn't need to add a DOM Listener. 您不需要添加DOM侦听器。 The map should just load with this script: 地图应该加载此脚本:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&callback=initMap">
</script>

and the initMap function. 和initMap函数。

EDIT: The DOM Listener is waiting for you to "load" the DOM so is waiting for you to open teh Console before loading the map. 编辑:DOM侦听器正在等待您“加载”DOM,因此等待您在加载地图之前打开控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM