问题描述:

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)

from the second stack question I got a link which helps me with part of the code but 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

 <div id="map-canvas"/>

css

html { height: 100% }

body { height: 100%; margin: 0; padding: 0 }

#map-canvas { height: 100% }

网友答案:

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.

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); 
});
相关阅读:
Top