首页 > 解决方案 > 谷歌地图未在嵌套 div 中呈现

问题描述

我正在使用 [this][1] 教程在我的网页上呈现谷歌地图。当我按照本教程中的方式使用它时,它工作正常。但它不会呈现在我的网页上。

我有一个选项卡式网页。每个选项卡内容都使用包含其 id 的 div 打开。因此,当我将具有地图 id 的 div 用于渲染地图功能来渲染地图时,它位于 Live Map 选项卡的 div 内。它不工作。

这是我的代码:

我网页上的标签式 HTML:

<div class="tab"> //tabs defined
  <button class="tablinks" onclick="openCity(event, 'tab1')">tab1</button>
  <button class="tablinks" onclick="openCity(event, 'tab2')">tab2</button>
  <button class="tablinks" onclick="openCity(event, 'Live-Map')">Live Map</button>
</div>

<div id="Live-Map" class="tabcontent"> //map div inside tab div
<div id="map"></div>  //map div
</div>

<script> // tab selector js function
function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}
</script>

编辑

CSS

这是CSS。尝试其他来源的解决方案,我发现父 div 的高度需要设为 100%。我也这样做了,但仍然没有成功。

 #map {
   height: 100%;
 }
#Live-Map {
   height: 100%;
 }
 /* Optional: Makes the sample page fill the window. */
 html, body {
 height: 100%;
 margin: 0;
 padding: 0;
}

编辑

我用位搜索解决了这个问题。问题基本上是必须给包装器 div 也 100% 的高度和宽度以及引导容器 div。因为 Google API 需要这些参数来渲染,

 #Live-Map, #map {
       height: 100%;
        width: 100%;
     }
   /* Optional: Makes the sample page fill the window. */
     html, body {
     height: 100%;
     width: 100%;
     margin: 0;
     padding: 0;
}

<div style="Height:100%; Width:100%;" class="container-fluid">

标签: javascripthtmlgoogle-maps

解决方案


如果在第一次演示期间地图不可见,则地图不起作用..在这种情况下,您可以在 openCity 函数中直接添加 initMap 的代码

    function openCity(evt, cityName) {

    var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(60.378920, 24.741850),
          zoom: 7
        });

    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

推荐阅读