Reputation: 2238
I have a google map set with the Javascript API V3. It's displayed in a div with a dynamic width, as a content pane slides up when we click on a marker.
Everything works fine, but one thing: When the pane slides up, the width of the map is changed, and so the center is displaced to the right (the pane is on the left). It is really inconvienient especially for small resolutions, where you can't even see the center after the pane is open.
I've tried the 'resize' trigger, but it doesn't seem to work... Any ideas ?
Thanks a lot !
Upvotes: 34
Views: 47163
Reputation: 2693
Calling resize
by it self will not acheive what you need.
What you need to do is first (before a resize occurs) get the current center of the map
var currCenter = map.getCenter();
Then you need to do something like the following, after your div is resized.
google.maps.event.trigger(map, 'resize');
map.setCenter(currCenter);
Should do the trick
UPDATE 2018-05-22
With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map
class.
The documentation states
When the map is resized, the map center is fixed
The full-screen control now preserves center.
There is no longer any need to trigger the resize event manually.
source: https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize");
doesn't have any effect starting from version 3.32
Upvotes: 87
Reputation: 3428
First set a variable for the current center, then use a event listener to detect a resize, and thusly set center.
//Get current center
var getCen = map.getCenter();
//Use event listener for resize on window
google.maps.event.addDomListener(window, 'resize', function() {
//Set Center
map.setCenter(getCen);
});
Upvotes: 18
Reputation: 1115
Hy there try this ;)
On map initialization
var currentMapCenter = null;
google.maps.event.addListener(map, 'resize', function () {
currentMapCenter = map.getCenter();
});
google.maps.event.addListener(map, 'bounds_changed', function () {
if (currentMapCenter) {
// react here
map.setCenter(currentMapCenter);
}
currentMapCenter = null;
});
After this just call when tou want the map resize.
google.maps.event.trigger(map, 'resize');
Upvotes: 2
Reputation: 1519
omarello does work but I can't upvote it. You probably forgot to refer to the var that defines your center coordinates. All "resize" does is pull the divs current width and height, it does not change anything about the map--yet!
var center = new google.maps.LatLng(39.5, -98.3);
$(document).ready(function() {
$("#fullsize").click(function(e) {
e.preventDefault();
$("#map_canvas").css({
width: '1000px'});
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
Upvotes: 7