javascript 隐藏 div 中的 Google Map V3 偏离中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4528490/
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-10-25 14:00:53  来源:igfitidea点击:

Google Map V3 off center in hidden div

javascriptgoogle-mapsgoogle-maps-api-3

提问by user547794

I have a google map inside a div that I need to be hidden by default

我在 div 中有一个谷歌地图,我需要默认隐藏

<div id="newpost" style="display:none;">

When the map is unhidden a part of it isn't rendering. I'm guessing I have to reload the map onSubmit. Anybody know how to do this?

当地图被取消隐藏时,它的一部分不会被渲染。我猜我必须在提交时重新加载地图。有人知道怎么做吗?

Thanks!

谢谢!

Here's my code:

这是我的代码:

   <script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('#newcatchhide').live('click', function(event) {        
         jQuery('#newpost').toggle('show');
    });
});

This is the map oad function on the body tag:

这是 body 标签上的 map oad 函数:

<body onload="load()" onunload="GUnload()">

Here is the div that is toggled, and the div that contains the map:

这是切换的 div 和包含地图的 div:

<div id="newpost" style="display:none;">
  <div id="map" style="width: 500px; height: 300px"></div>

回答by ifaour

Something like this? http://jsbin.com/imuri5
The idea is to initialize the map afterdisplaying the DIV.

像这样的东西?http://jsbin.com/imuri5
思路是显示DIV初始化地图。

EDIT:
Ok based on your update replace:

编辑:
好的,根据您的更新替换:

jQuery('#newcatchhide').live('click', function(event) {        
         jQuery('#newpost').toggle('show');
    });

with:

和:

var onLoad = true;
jQuery('#newcatchhide').live('click', function(event) {        
    jQuery('#newpost').toggle(function() {
        if(onLoad) {
            load();
            onLoad = false;
        }
    });
});

And then remove onload="load()"from the body tag

然后onload="load()"从body标签中删除

回答by Jani Hartikainen

I recently had this same issue myself and discovered the fix to be quite simple:

我最近自己也遇到了同样的问题,发现修复方法非常简单:

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

Where mapis your google map instance.

map你的谷歌地图实例在哪里。

You can call this after you make your div visible.

您可以在使 div 可见后调用它。

If you use jQuery for the map, you can use

如果您对地图使用 jQuery,则可以使用

map = $('#map_canvas').gmap().map;

回答by Крайст

better:

更好的:

gmap.redraw = function() {
    gmOnLoad = true;
    if(gmOnLoad) {
        google.maps.event.trigger(gmap, "resize");
        gmap.setCenter(gmlatlng);
        gmOnLoad = false;
    }
}

and in show click event:

并在显示点击事件中:

$("#goo").click(function() {
  if ($("#map_canvas").css("display") == "none") {
    $("#YMapsID").toggle();
    $("#map_canvas").toggle();
    if (gmap != undefined) {
        gmap.redraw();
    }
  }
});