谷歌地图在 jQuery 标签中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9458215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:50:02  来源:igfitidea点击:

Google Maps Not Working in jQuery Tabs

jquerygoogle-mapsgoogle-maps-api-3tabsjquery-tabs

提问by Joe

Google maps not working when placed inside jQuery tabs is a question that's all over the web. In my research so far none of the solutions seem to work. Hopefully someone here can help...

放置在 jQuery 选项卡中时 Google 地图不起作用是整个网络上的一个问题。到目前为止,在我的研究中,似乎没有一个解决方案有效。希望这里有人可以帮助...

This is a screenchot of the error in Firefox 10, Chrome 17, Safari 5.1.2, Opera 11.61. http://www.flickr.com/photos/75523633@N04/6932970713/

这是 Firefox 10、Chrome 17、Safari 5.1.2、Opera 11.61 中错误的屏幕截图。 http://www.flickr.com/photos/75523633@N04/6932970713/

The error is not present in IE8 and is intermittant in 9. In Firefox, it goes away when you open FireBug.

该错误在 IE8 中不存在,在 9 中是间歇性的。在 Firefox 中,当您打开 FireBug 时它就会消失。

The site is in Wordpress 3.3.1 and the map is generated/retrieved via a plugin. It does not seem to matter which maps plugin I use; the error remains the same. Based on my research, this appears to be js/jQuery problem between the tabs and the Google Map API javascript, not a Wordpress/plugin problem.

该站点位于 Wordpress 3.3.1 中,地图是通过插件生成/检索的。我使用哪个地图插件似乎并不重要;错误保持不变。根据我的研究,这似乎是选项卡和 Google Map API javascript 之间的 js/jQuery 问题,而不是 Wordpress/插件问题。

Here is my code. Right now, I'm using the wp-gmappity-easy-google-maps plugin for the maps, but I have also tried the comprehensive-google-map-plugin. Both work great outside the tabs.

这是我的代码。现在,我正在为地图使用 wp-gmappity-easy-google-maps 插件,但我也尝试了全面的 google-map-plugin。两者都在标签外工作得很好。

HTML:

HTML:

// Header calls:
<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>
<script type='text/javascript' src='http://xxxxxxxxxx.com/wp-content/themes/zzzzzzzzzz/scripts/tabs.min.js'></script>
// HTML Body:
<div class="tabs_framed_container">
<ul class="tabs_framed">
    <li><a href="#">Tab 1</a></li>
    <li><a href="#">Tab 2</a></li>
    <li><a href="#">Tab 3</a></li>
    <li><a href="#">Map Tab</a></li>
    <li><a href="#">Tab 3</a></li>
</ul>
<div class="tabs_framed_content">
    <h2>Tab 1 Content</h2>
    <!-- Some Content -->
</div>
<div class="tabs_framed_content">
    <h2>Tab 2 Content</h2>
    <!-- Some Content -->
</div>
    <h2>Tab 3 Content</h2>
    <!-- Some Content -->
</div>
<div class="tabs_framed_content">
    <div class="map_container">
        <div style="width:900px;margin-left:auto;margin-right:auto;">
            <div class="wpgmappity_container" id="wpgmappity-map-1" style="width:900px;height:400px;margin-left:auto;margin-right:auto;"></div>
        </div>
        <script type="text/javascript">
            function wpgmappity_maps_loaded1() {
            var latlng = new google.maps.LatLng(42.4005322,-71.2750094);
            var options = {
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                zoomControl : true,
                zoomControlOptions :
                {
                    style: google.maps.ZoomControlStyle.SMALL,
                    position: google.maps.ControlPosition.TOP_LEFT
                },
                mapTypeControl : true,
                mapTypeControlOptions :
                {
                    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                    position: google.maps.ControlPosition.TOP_RIGHT
                },
                scaleControl : true,
                scaleControlOptions :
                {
                    position: google.maps.ControlPosition.TOP_LEFT
                },
                streetViewControl : true,
                streetViewControlOptions :
                {
                    position: google.maps.ControlPosition.TOP_LEFT
                },
                panControl : false,  zoom : 14
            };
            var wpgmappitymap1 = new google.maps.Map(document.getElementById('wpgmappity-map-1'), options);
            var point0 = new google.maps.LatLng(42.4005322,-71.2750093);
            var marker1_0 = new google.maps.Marker({
                icon : 'http://xxxxxxxxxx.com/wp-content/themes/zzzzzzzzzz/images/mapmarker.png',
                position : point0,
                map : wpgmappitymap1
                });
            }
            jQuery(window).load(function() {
                wpgmappity_maps_loaded1();
            });
        </script>
    </div>
</div>
<div class="tabs_framed_content">
    <h2>Tab 2 Content</h2>
    <!-- Some Content -->
</div>

Here is the relevant CSS:

这是相关的CSS:

.tabs_framed{padding:0;margin:0;list-style-type:none;clear:left;height:25px;border-bottom:1px solid #E5E5E5;}
.tabs_framed_container{margin-bottom:40px;}
.tabs_framed a{
    display:block; position:relative; background:#fafafa; border:1px solid #E5E5E5; padding:7px 30px; margin-right:2px;
    font-size:10px; text-decoration:none; text-transform:uppercase; letter-spacing:1px; line-height:10px; color:#777;
    opacity:1; -webkit-transition:all .5s ease; -moz-transition:all .5s ease; -o-transition:all .5s ease; transition:all .5s ease;
}
.tabs_framed a:hover{color:#20548B;text-decoration:none;background:#fff;}
.tabs_framed a.current{color:#000;cursor:default;border-bottom:1px solid #fff;background:#fff;}
.tabs_framed li,{padding:0;margin:0;list-style-type:none;float:left;}
.tabs_framed_content{display:none;background-color:#fff;border:1px solid #E5E5E5;border-width:0 1px 1px 1px;padding:30px 30px 15px 30px;}

div.wpgmappity_container img { 
    background-position: 0% 0%;
    background-color: none !important;
    max-width: none !important;
    background-image: none !important;
    background-repeat: repeat !important;
    background-attachment: scroll !important;
}

Here is a link to the file that governs my tabs: http://themes.mysitemyway.com/awake/wp-content/themes/awake/lib/scripts/tabs.min.js

这是管理我的选项卡的文件的链接:http: //themes.mysitemyway.com/awake/wp-content/themes/awake/lib/scripts/tabs.min.js

flowplayer.org/tools/forum/25/79274 is one solution I found (scroll to bottom). However, the checkResize and resizeMap no longer work (see api reference at code.google.com/apis/maps/documentation/javascript/reference.html#Map, scroll down a little to "Events" and find google.maps.event.trigger(map, 'resize') which is apparently the replacement code). www.raymondcamden.com/index.cfm/2009/6/5/jQuery-Tabs-and-Google-Maps is another writeup that is too old.

flowplayer.org/tools/forum/25/79274 是我找到的一种解决方案(滚动到底部)。但是,checkResize 和 resizeMap 不再有效(请参阅 code.google.com/apis/maps/documentation/javascript/reference.html#Map 上的 api 参考,向下滚动到“事件”并找到 google.maps.event。 trigger(map, 'resize') 这显然是替换代码)。www.raymondcamden.com/index.cfm/2009/6/5/jQuery-Tabs-and-Google-Maps 是另一篇过时的文章。

I've seen this proposed:

我已经看到这个提议:

jQuery(document).ready(function(){
jQuery('.tabs_container').bind('tabsshow', function(event, ui) {
    if (ui.panel.id == "map-tab") {
        google.maps.event.trigger(map, 'resize');
    }
});
});

but I have no idea how to implement it (tried a few ways with no success) or if it would even work.

但我不知道如何实现它(尝试了几种方法都没有成功)或者它是否会起作用。

From all my research, it looks like you have to trigger a map resize event when the tab containing the map is selected. So far, I've had no luck adapting any of the solutions out there - espceially since I'm mot familiar with js/jQuery. It seems like someone familiar with js or jQuery could solve this.

从所有的研究中,它看起来您必须触发包含地图的选项卡时触发映射调整大小事件。到目前为止,我没有运气适应那里的任何解决方案 - 特别是因为我不熟悉 js/jQuery。似乎熟悉 js 或 jQuery 的人可以解决这个问题。

Please help me.

请帮我。

采纳答案by Joe

I abandoned the plugins and went with the google maps shortcode that has been released for the theme I'm using. While I lose the custom markers functionality, the theme developers were finally able to help get this all working. They added the following code to the shortcode PHP file.

我放弃了插件并使用了为我正在使用的主题发布的谷歌地图简码。虽然我失去了自定义标记功能,但主题开发人员终于能够帮助完成这一切。他们将以下代码添加到短代码 PHP 文件中。

jQuery('ul.tabs_framed').data('tabs').onClick(function(e,index) {
    resizeMap(" . 'map'.$map_id .") 
});
function resizeMap(m) {
    x = m.getZoom();
    c = m.getCenter();
    google.maps.event.trigger(m, 'resize');
    m.setZoom(x);
    m.setCenter(c);
};

This code triggers a map reload when the tab containing the map is clicked. It also recenters the map. This solution solved the problem for me and the google maps now display in the jquery tabs. Hopefully some of the more javascript-savvy users here (and plugin developers!!!) can adapt this solution to their own maps-in-tabs issues.

当单击包含地图的选项卡时,此代码会触发地图重新加载。它还对地图进行了重定位。这个解决方案为我解决了这个问题,谷歌地图现在显示在 jquery 选项卡中。希望这里的一些更精通 javascript 的用户(和插件开发人员!!!)可以将此解决方案应用于他们自己的标签中地图问题。

回答by Jason Maggard

rogercut's answer got me where I needed to be. I am using Bootstrap tabs, nested, and could not get the map to update.

rogercut 的回答让我到达了我需要去的地方。我正在使用嵌套的 Bootstrap 选项卡,但无法更新地图。

When I click on tab group 2 (#tg2), the map tab is the first one showing. I also needed to fire the resize if someone clicked the second level tab (#tab1) from within tab group 2.

当我单击选项卡组 2 (#tg2) 时,地图选项卡是第一个显示的。如果有人从选项卡组 2 中单击第二级选项卡 (#tab1),我还需要触发调整大小。

The click handler works, but the problem is that on click, the tab is still hidden... By setting a small delay, it gives time for the tab to show before the resize fires off.

单击处理程序可以工作,但问题是在单击时,选项卡仍然隐藏...通过设置一个小的延迟,它可以在调整大小触发之前让选项卡有时间显示。

// Create Map
var map;
function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(48.8582, 2.2945), //I see Paris, I see France
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
 map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);
}

//Bind click handlers - Here's the important part
$('a[href=#tab1], a[href=#tg2]').on('click', function() {
    setTimeout(function(){
        google.maps.event.trigger(map, 'resize');
    }, 50);
});

So, we're telling the browser to wait 50ms after the click to do the resize. In my testing, 50ms was plenty of time for the tab to show, yet short enough that it's not really noticeable to the user. In fact, my testing worked with a delay of only 1ms on the 4-5 machines I tested it on - even a dog slow laptop we had sitting in storage. 50ms is just being safe.

所以,我们告诉浏览器在点击后等待 50 毫秒来调整大小。在我的测试中,50 毫秒足以让选项卡显示出来,但也足够短,以至于用户不会真正注意到它。事实上,我的测试在我测试的 4-5 台机器上只有 1 毫秒的延迟 - 即使是我们存放在存储中的慢速笔记本电脑。50ms 只是为了安全。

Hope this helps someone else.

希望这对其他人有帮助。

回答by user1631533

The problem (as stated above and in other places) is that the map div must be visible in order to work. So load the map in a tab that is visible. Then if you wish, change to the tab you want to display.

问题(如上文和其他地方所述)是地图 div 必须可见才能工作。因此,在可见的选项卡中加载地图。然后,如果您愿意,请更改为您要显示的选项卡。

To do this I added a one-time event listener to the map. Inside that function I changed to the first tab. During the load, you do see the map area for about a second before the tab is changed. The advantage is that the user has to do nothing for this to work.

为此,我向地图添加了一个一次性事件侦听器。在该功能中,我更改了第一个选项卡。在加载期间,您会在更改选项卡之前看到地图区域大约一秒钟。优点是用户无需执行任何操作即可使其工作。

google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
     $("#Tabs").tabs('select',0);
});

回答by user3371536

Before I have the same problem for implementing google-map inside tabs, specially when the map is not in the first selection. But I have tried and it's work with a simple solution like this :

在我在标签内实现 google-map 遇到同样的问题之前,特别是当地图不在第一选择中时。但我已经尝试过,它可以使用这样的简单解决方案:

Make a simple js function :

做一个简单的js函数:

<script type="text/javascript">

function ResetMap() {
google.maps.event.trigger(map, 'resize');
}

</script>


<li><a href="#tab1">Select Tab1</a></li>
<li onClick="ResetMap();"><a href="#tab2">Select Google Map</a></li>

<div class="tab1-content" id="tab1">Content tab1</div>
<div class="tab2-content" id="tab2"><?php include_once ('google-map.php') ?></div>

回答by user3737572

I solved this for the bootstrap Tab. It is just the matter of calling resize map function right after the map container is displayed.

我为引导标签解决了这个问题。这只是在显示地图容器后立即调用调整大小地图功能的问题。

I have added the following out side the initialize() function:

我在 initialize() 函数之外添加了以下内容:

jQuery('.nav-tabs a[href="#my-map"]').on('shown.bs.tab', function(){
         google.maps.event.trigger(map, 'resize');
         map.setZoom(15); //You need to reset zoom
         map.setCenter(myLatlng); //You need to reset the center
    });

回答by stefan

This might not work for everyone! One solution that worked for me was to have the hidden tabs display but somewhere "not visible" to the user. This will allow the map to render even though is not in first/active tab. Find a way to target the hidden tabs ONLY:

这可能不适用于所有人!对我有用的一种解决方案是显示隐藏的选项卡,但在用户“不可见”的某个地方。这将允许地图渲染,即使它不在第一个/活动选项卡中。找到一种仅定位隐藏标签的方法:

.tab-hidden{
    position: absolute !important;
    left: -10000px !important; /* maybe not that much */
    display:block !important;
    width:100% !important; /* I found this to be very important*/
}

Map width 100% and not a fixed width.

地图宽度 100% 而不是固定宽度。

回答by Graham Walker

No of the above answers are completely correct. The problem occurs because the map canvas is set to width:0; height:0 by default before loading and then expects you to either pass the dimension or get the dimensions from the parent, as this is inside jQuery tabs there are no dimensions.

以上答案没有一个是完全正确的。出现问题是因为地图画布设置为width:0;加载前默认情况下 height:0 ,然后期望您传递维度或从父级获取维度,因为这是在 jQuery 选项卡中没有维度。

As mentioned above bind to the click event of your tab and set the map_canvas dimension then call the google.maps.event.trigger()

如上所述绑定到选项卡的点击事件并设置 map_canvas 维度,然后调用 google.maps.event.trigger()

 $(function(){

$('#maptab').bind('click',function() {
            var w = $('#map_view').width();
            var h = $('#map_view').height();
            $('#map_canvas').css({ width: w, height: h });
           google.maps.event.trigger(map, 'resize');

        });

});

回答by rogercut

When developing a website which included a map tab content I ran into the same issue. The site is http://samet.com.ar(in spanish, click on the map icon or the 'ubicacion' link). The same error you mention arose whenever the tab div loaded together with the other ones in its tab group. I've found out that if I could manage to give it some time to load after the other tabs did, then there wouldn't be any problem.

在开发包含地图选项卡内容的网站时,我遇到了同样的问题。该站点是http://samet.com.ar(在西班牙语中,单击地图图标或“ubicacion”链接)。只要标签Div与其选项卡组中的其他选项卡一起加载时,就会提及的错误。我发现如果我能在其他选项卡加载后给它一些时间来加载它,那么就不会有任何问题。

I could afford to do that because anyway I gave some 3.5 sec for the wrapper to show up in order to get all the background photos loaded and the map is in an invisible tab at load time, so I don't need it to show up right away.

我负担得起这样做,因为无论如何我给了一些 3.5 秒的时间让包装器显示出来,以便加载所有背景照片,并且地图在加载时位于一个不可见的选项卡中,所以我不需要它显示马上。

The map tab then loads as a callback function right after the whole wrapper does. If you inspect the page, look for id 'pane-container'. Inside 'panes' you'll find the map div loaded at the end.

然后,在整个包装器完成之后,地图选项卡作为回调函数加载。如果您检查页面,请查找 ID 'pane-container'。在“窗格”中,您会发现最后加载的地图 div。

The relevant jQuery code I'm using in the index.php page is as follows:

我在 index.php 页面中使用的相关 jQuery 代码如下:

<script type='text/javascript'>
   ( function( $ ) {
     // for SOF post --- previous code deleted ---
     $( "#wrapper" ).delay( 3500 ).fadeIn( "slow",function() {
     // Animation complete
     <?php $post_map = get_posts('name=map');?>
     $( "#map" ).delay( 1000 ).append( <?php echo "'".$post_map[0]->post_content."'"; ?> );
            } );
 } )( jQuery );
</script>

I hope this helps somehow. Forgot to mention that the map code is embedded as a content in a specific post. (BTW, the map marker is located on the upper right on purpose to show the main access roads.)

我希望这会有所帮助。忘记提及地图代码作为内容嵌入到特定帖子中。(顺便说一句,地图标记特意位于右上角以显示主要通道。)

Cheers!

干杯!

回答by user3371536

Its work for me, meet my requirement, and you may use it as reference:

它对我的工作,满足我的要求,你可以作为参考:

<script type="text/javascript">

function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function getCookie (name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset);
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    if (setStr == 'false') {
        setStr = false;
    } 
    if (setStr == 'true') {
        setStr = true;
    }
    if (setStr == 'null') {
        setStr = null;
    }
    return(setStr);
}

function hidePopup() {
    setCookie('popup_state', false); 
    document.getElementById('popup').style.display = 'none';
    document.getElementById('hiding').style.display = 'block';

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

function showPopup() {
    setCookie('popup_state', null);
    document.getElementById('popup').style.display = 'block';
    document.getElementById('hideup').style.display = 'none';

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

function checkPopup() {
    if (getCookie('popup_state') == null) { // if popup was not closed
        document.getElementById('popup').style.display = 'block';
        document.getElementById('hiding').style.display = 'block';

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

  }   
}

</script>


<body onload="checkPopup();">

    <div class="map-button" id="hiding"><a href="#" onclick="showPopup(); return false;"><img src="images/map_magnify.png" alt="" title="Show Google Map" ></a></div>

    <div class="map-button" id="popup" style="display:none"> <a href="#" onclick="hidePopup(); return false;"><img src="images/map_delete.png" alt="" title="Hide Google Map" ></a>
    <div id="gmap"></div>
    </div>
</body>

Note : You can make CSS class 'map-button' for positioning the button as required. Put your own image buttom. Replace id="gmap" as yours. Hope it helps you.

注意:您可以根据需要制作 CSS 类“map-button”来定位按钮。把你自己的图像按钮。将 id="gmap" 替换为您的。希望对你有帮助。

回答by SAID BEHAINE

Try this in the css:

在css中试试这个:

.tab-content > .tab-pane:not(.active), 
.pill-content > .pill-pane:not(.active) {
 display: block;
 height: 0;
 overflow-y: hidden;
}