jQuery 谷歌地图响应式调整大小

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

Google maps responsive resize

javascriptjquerygoogle-maps-api-3

提问by rob.m

I'm trying to get google maps responsive and resize while keeping its center when windows resizes. I read other stack questions in regards such as:

我试图让谷歌地图响应并调整大小,同时在窗口调整大小时保持其中心。我阅读了其他堆栈问题,例如:

Responsive Google Map?and Center Google Maps (V3) on browser resize (responsive)

响应式谷歌地图?在浏览器调整大小(响应式)上居中 Google Maps (V3)

from the second stack question I got a link which helps me with part of the codebut I still have no luck. This is the code I am using, when I resize the window, the maps doesn't resize at all

从第二个堆栈问题我得到了一个链接,它可以帮助我处理部分代码,但我仍然没有运气。这是我正在使用的代码,当我调整窗口大小时,地图根本不会调整大小

    function initialize() {
      var mapOptions = {
       center: new google.maps.LatLng(40.5472,12.282715),
       zoom: 6,
       mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize);
    google.maps.event.addDomListener(window, "resize", function() {
     var center = map.getCenter();
     google.maps.event.trigger(map, "resize");
     map.setCenter(center); 
    });

html

html

 <div id="map-canvas"/>

css

css

html { height: 100% }
body { height: 100%; margin: 0; padding: 0; }
#map-canvas { height: 100%; }

回答by rsnickell

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

将您的地图变量移动到事件侦听器可以使用它的范围内。您正在 initialize() 函数中创建地图,并且以这种方式创建时没有其他任何东西可以使用它。

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});