Using Google Maps V3 Javascript API you can keep the map centered to the browser’s window by using the following trick when resizing the window.
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(0,0), mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// this is our gem
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Code language: JavaScript (javascript)
Thank you!!!!
Fantastic! You can re-center the map on a specific point if moved by supplying coordinates on var center instead of map.getCenter().
Thank you
Hi. Where do you ‘put’ the code please? Thank you
Around where you usually declare your ‘map’ variable in your javascript code.
Thank you, works great. A lot of incomplete answers on stackoverflow.
No problem, this is quite a simple solution that works well.
Thanks for this. Works perfectly. That’s saved me trawling the web looking for the answer!
Thanks a lot!
Excellent! Simple and clear. Thank you very much for this snippet.
Thank You! This is exactly what I have been trying to do. I was tooling with so much more than needed such as, getCenter on resize and getCenter on center_changed, but the problem was that the center was being reset on resize too so when ever i would resize, a new value for center was set and then that value was set as the center position, essentially doing nothing, just causing a stupid loop!
Glad it helped 😉
Sorry but the code doesn’ t show the body
the body has the div open and closed of
div id=”map_canvas” and closure /div
sorry but I’m not a good user
Dear all, I’ve tried to use the above code but I’ve done everything to obtain nothing. Following code is the last I’ve tried with no result:
Documento senza titolo
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(-34.397, 150.644), mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// this is our gem
google.maps.event.addDomListener(window, 'resize', function() {
var center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
Please help me to understand where it’ swrong
thank you
Yep, this worked a treat, thanks for posting it!
That works, thank you ð
Brilliant. Spent hours on this trying with my limited JS skills. Thanks!!!
Nice code! Works like a charm!
Excellent piece of code. Thanks heaps. It worked perfectly!
Brilliant! Works like a charm!! Thank you!!!
THANKYOU! Worked a treat for me!