Center Google Maps (V3) on browser resize (responsive)
I have a Google Maps (V3) in my page at 100% page width with one marker in the middle. When I resize my browser window's width I would like the map to stay centered (responsive). Now the map just stays at the left side of the page and gets smaller.
UPDATE Got it to work exactly as described thanks to duncan. This is the final code:
var center;
function calculateCenter() {
center = map.getCenter();
}
google.maps.event.addDomListener(map, 'idle', function() {
calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(center);
});
You need to have an event listener for when the window resizes. This worked for me (put it in your initialize function):
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(center);
});
Detect the browser resize event, resizes the Google Map while preserving the center point:
var map = ...; // your map initialisation code
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
You can use the same code in other event handlers when resizing the google map via other means (e.g. with a jQuery-UI 'resizable' control).
Source: http://hsmoore.com/blog/keep-google-map-v3-centered-when-browser-is-resized/ credit to @smftre for the link.
Note: This code was linked in @smftre's comment on the accepted answer. I think it's worth adding it as its own answer since it is really superior to the accepted answer. It eliminates the need of a global variable to track the center point and an event handler to update that variable.
Some good examples on w3schools.com. I used the following and it works great.
google.maps.event.addDomListener(window, 'resize', function() {
map.panTo(myLatlng);
});
http://www.w3schools.com/googleapi/google_maps_events.asp