[英]Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag
我正在嘗試將顯示地圖的div
標簽( <div id="map-canvas"></div>
)放置在另一個div
,但不會以這種方式顯示地圖。 是CSS還是JavaScript問題? 還是僅僅是API的工作方式?
這是嵌套div
代碼:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div> <!-- ommiting this div will show the map -->
<div id="map-canvas"></div>
</div>
</body>
</html>
問題在於百分比大小。 您沒有定義父div的大小(新的div),因此瀏覽器無法將大小報告給Google Maps API。 給包裝器div指定一個特定的大小,或者如果可以確定其父對象的大小,則給一個百分比大小將起作用。
請參閱Mike Williams的Google Maps API v2教程中的以下說明 :
如果嘗試在地圖div上使用style =“ width:100%; height:100%”,則會得到高度為零的地圖div。 這是因為div嘗試占
<body>
大小的百分比,但默認情況下<body>
的高度不確定。有很多方法可以確定屏幕的高度並將像素數量用作地圖div的高度,但是一種簡單的替代方法是更改
<body>
使其高度為頁面的100%。 我們可以通過對<body>
和<html>
都應用style =“ height:100%”來實現。 (我們必須對兩者都進行此操作,否則<body>
嘗試達到文檔高度的100%,並且默認值是不確定的高度。)
將100%的大小添加到HTML和CSS中的正文中
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
內聯添加到沒有id的所有div中:
<body>
<div style="height:100%; width: 100%;">
<div id="map-canvas"></div>
</div>
</body>
添加style="width:100%; height:100%;"
到div看看有什么用
不是#map_canvas
而是主要div
例
<body>
<div style="height:100%; width:100%;">
<div id="map-canvas"></div>
</div>
</body>
這里還有其他答案,解釋了為什么這樣做是必要的
我用以下方法解決了這個問題:
<div id="map" style="width: 100%; height: 100%; position: absolute;">
<div id="map-canvas"></div>
</div>
固定
給出div的初始高度,並以樣式中的百分比指定高度;
#map {
height: 100%;
}
<div id="map" style="clear:both; height:200px;"></div>
以我為例,我得到的是灰色背景,結果是在地圖選項中包含了一個縮放值。 是的,沒有道理。
巫師
您是否嘗試過設置額外div的高度和寬度,我知道在我正在使用JS進行的項目中,除非已經設置了高度和寬度,否則不會在div中放置任何內容。
我使用了您的代碼,並對高度和寬度進行了硬編碼,但對我來說卻顯示出來了,沒有它不會顯示出來。
<body>
<div style="height:500px; width:500px;"> <!-- ommiting the height and width will not show the map -->
<div id="map-canvas"></div>
</div>
</body>
我建議您對其進行硬編碼或為div分配一個ID,然后將其添加到您的CSS文件中。
我只是想添加對我有用的東西,我在兩個div中都添加了高度和寬度,並使用了引導程序使其具有響應性
<div class="col-lg-1 mapContainer">
<div id="map"></div>
</div>
#map{
height: 100%;
width:100%;
}
.mapContainer{
height:200px;
width:100%
}
為了使col-lg-1
工作,請在此處添加引導程序參考
理解此問題已解決,但是上面提供的解決方案可能無法在所有情況下都有效。
就我而言
<div style="height: 490px; position:relative; overflow:hidden">
<div id="map-canvas"></div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.