谷歌地图响应调整大小

时间:2013-08-26 12:32:56

标签: javascript jquery google-maps-api-3

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

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

来自第二个堆栈问题I got a link which helps me with part of the code,但我仍然没有运气。这是我正在使用的代码,当我调整窗口大小时,地图根本不会调整大小

    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

 <div id="map-canvas"/>

CSS

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

2 个答案:

答案 0 :(得分:100)

将地图变量移动到事件侦听器可以使用的范围内。您正在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); 
});

答案 1 :(得分:0)

几年后,我转到了传单地图,并且已经完全解决了此问题,以下内容也可以应用于Google地图:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });