Keep Google Map v3 centered when browser is resized

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);
});

14 thoughts on “Keep Google Map v3 centered when browser is resized

  1. 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

  2. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>