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

Answers:

Answer

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

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.

Answer

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

Answer

html: Create a div with an id of your choice

<div id="map"></div>

js: Create a map and attach it to the div you just created

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 16,
    center: new google.maps.LatLng(-33.890542, 151.274856)
});

Center when the window resizes

var center = map.getCenter();

google.maps.event.addDomListener(window, 'resize', function() {
    map.setCenter(center);
});
Answer

Updated of the above solution to es6.

let center;
const addMapListener = google.maps.event.addDomListener;

addMapListener(map, 'idle', () => center = map.getCenter());
addMapListener(window, 'resize', () => map.setCenter(center));

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.