推迟谷歌地图初始化,直到显示引导标签

use*_*727 2 jquery google-maps-api-3 twitter-bootstrap-3

我已经研究了很多,似乎很多人在这里遇到了和我一样的问题,但是我无法弄清楚如何修复它.

基本上我正在隐藏的bootstrap选项卡中初始化谷歌地图.当我点击药丸使标签可见时,只显示地图的一小部分.

从我收集到的,这是因为地图正在隐藏元素中初始化.所以我需要在标签变得可见之后初始化地图.

我已经尝试过,我已经尝试过,但我无法正确使用代码.任何帮助都将是宏伟的 - 我如何使地图仅在标签可见后执行?

提前致谢

<!-- this is the hidden tab-->
<div class="tab-pane map-pane" id="map<?php echo $country_slug; ?>">

<div class = "row">
    <div class = "col-md-12">
      <div id="map-canvas" class = "map-canvas"></div>
    </div>
    </div>

    <!--and here is the map which executes inside the hidden tab-->
    <!--how can i cause this script to delay execution until the tab is shown?-->
<script type="text/javascript">

function initialize() {
    var mapOptions = {
       center: new google.maps.LatLng(22.39813,114.10943),
       zoom: 8
    };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
    mapOptions);

        }
    google.maps.event.addDomListener(window, 'load', initialize);
Run Code Online (Sandbox Code Playgroud)

Zim*_*Zim 7

您应该能够将处理程序附加到Bootstrap选项卡show事件.

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    initialize();
});
Run Code Online (Sandbox Code Playgroud)

工作演示:http://bootply.com/102241


MrU*_*own 6

http://bootply.com/102479

在地图选项卡链接中添加ID,以便更容易识别.显示相应的选项卡内容时触发地图调整大小事件.

这样,地图仅初始化一次,而前一个答案不是这种情况.

请注意,您需要在initialize函数之外定义map变量.