RSS
magnify
Home Google Keep Google Map v3 centered when browser is resized
formats

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

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
14 Comments  comments 

14 Responses

  1. Skweekah

    THANKYOU! Worked a treat for me!

  2. Fluid

    Brilliant! Works like a charm!! Thank you!!!

  3. Ricvk

    Excellent piece of code. Thanks heaps. It worked perfectly!

  4. Walter

    Nice code! Works like a charm!

  5. Julie

    Brilliant. Spent hours on this trying with my limited JS skills. Thanks!!!

  6. Kemal Ersöz

    That works, thank you :)

  7. Yep, this worked a treat, thanks for posting it!

  8. mrzpro

    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

  9. mrzpro

    Sorry but the code doesn’ t show the body

  10. Rob Huska

    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!

  11. Ernesto

    Thanks a lot!

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>

© Copyright © 2012 · Web Development London UK · All rights reserved · Site hosted on the hsmoore.com network
By using the site and/or making use of any of our services you agree to our Terms and Conditions