簡體   English   中英

谷歌地圖現在顯示在您初始化時顯示無div

[英]google maps now showing when you initialize in a display none div

我正在初始化顯示div中的google地圖,但出現了問題,我只看到一個灰色方塊

<div style="display:none;"  id="divMap">
     <div id="map" style="width:300px; height:300px;"></div>
</div>
<button onclick="showMap();">test</button>

但是當我刪除style =“ display:none;”時 有用

我創建了一個提琴手https://jsfiddle.net/ka8nywrg/2/,您可以從這里進行測試。 按下按鈕時會顯示地圖

我應該怎么做才能防止這種情況?

代碼段 (摘自小提琴):

 var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); } function showMap(){ document.getElementById("divMap").style.display = 'block' } 
 /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } 
 <div style="display:none;" id="divMap"> <div id="map" style="width:300px; height:300px;"></div> </div> <button onclick="showMap();">show map</button> <!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script> 

當地圖各有變化時,最好在地圖上調用Maps API V3的resize方法。 地圖需要再次渲染。

google.maps.event.trigger(map, 'resize'); 

這應該對您有幫助! 每當您切換display:none屬性時,也只需調用上面的函數!

您需要做兩件事:

  1. 呼叫google.maps.event.trigger(map, 'resize'); 告訴地圖div的大小已更改。

  2. 確定div的大小后,重新設置地圖中心:

map.setCenter(mapCenter);

概念證明

代碼段:

 var map; var mapCenter = { lat: -34.397, lng: 150.644 }; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: mapCenter, zoom: 8 }); var marker = new google.maps.Marker({ map: map, position: map.getCenter() }) } function showMap() { document.getElementById("divMap").style.display = 'block' google.maps.event.trigger(map, 'resize'); map.setCenter(mapCenter); } 
 /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } 
 <div style="display:none;" id="divMap"> <div id="map" style="width:300px; height:300px;"></div> </div> <button onclick="showMap();">show map</button> <!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM