如何在jQuery应用程序的两个选项卡中添加谷歌地图

How to add Google Maps in two tabs of jQuery application

本文关键字:选项 两个 谷歌地图 添加 jQuery 应用程序      更新时间:2023-09-26

我的jQuery应用程序中有两个选项卡。我想在两个选项卡中都使用谷歌地图。我为下面的代码中显示的每个选项卡添加了脚本和两个<div>标记。

第一个选项卡:

<div class="map_canvas" style="width:100%; height:100%"></div> 

第二个选项卡:

<div class="map_canvas" style="width:100%; height:100%"></div> 

谷歌地图脚本:

function initialize() 
    {
            var latlng = new google.maps.LatLng(11.6952727, 77.5195312);
            var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementByClassName("map_canvas"),myOptions);
    }

----------Style for Google Map
.map_canvas { height: 100% }
#notes{ height: 100%;width:100% ; margin: 0px; padding: 0px }  // Tab1 div tag ,contains the First tab map Div Tag
#accordionWrapper{ height: 100%;width:100% ; margin: 0px; padding: 0px }// Tab2 div tag, contains the First tab map Div Tag

地图未显示在两个选项卡中。这里有什么问题?

正如您在这里看到的,getElementByClassName()按照找到的元素在树中的出现顺序返回它们的实时NodeList:您应该迭代该NodeList并为每个元素创建一个新的映射,因为我认为gmaps API不允许您这样做。

您需要使用map_canvas类迭代元素,并为每个元素创建一个新的Map实例,否则将无法工作。

我猜你是在使用jQuery UI选项卡吗?如果是这样的话,你很可能会在将谷歌地图加载到隐藏/非活动选项卡时遇到麻烦。正如评论中所提到的,已经存在关于这一点的问题,并附有解决这一问题的答案。

无论如何,对你的代码进行以下更改/添加,你就可以开始了!

CSS

.ui-tabs .ui-tabs-hide {
    position: absolute;
    left: -10000px;
}

JavaScript

$(function() {
    // Container for maps
    var maps = [],
        // Initial position
        latlng = new google.maps.LatLng(11.6952727, 77.5195312),
        // Options for Google Maps
        mapOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    // Iterate the canvas elements and create a new map instance
    $(".map_canvas").each(function(){
        maps.push(new google.maps.Map(this, mapOptions));
    });
    // Trigger map resize on tab change
    $('#id-of-tabs-container').bind('tabsshow', function(event, ui) {
        google.maps.events.trigger(maps[ui.index], 'resize');
    });
});

将临时id替换为元素的相应id。