I\'ve run into a problem where calling map.fitBounds seems to zoom out. I\'m trying to use the backbone.js router to save the map bounds in the url. I want to be able to boo
I got the same problem when after initializing the map called map.fitBounds(...)
. The behaviour I encountered was that if the fitBounds
method was called a few seconds after the map was initialized then no problem (the zoom was appropriate).
So first I started to call the fitBounds
method after the map was loaded, which on google maps translates to when the map is idle
.
google.maps.event.addListener(map, 'idle', function() {
var bounds = //define bounds...
map.fitBounds(bounds);
});
This actually works, however the idle
event is triggered almost constantly. And if there is any change to the map (drag, zoom, etc...) when this change stops, the map will fit the bounds again...
The problem is that calling the method only once does not work (either with a boolean to check if was already called, or with google.maps.event.addListenerOnce
because the first time the map is idle it still "isn't ready" for the bounds to be fitted. (From experience).
So my solution was to trigger the fitBounds
on a different event. Instead of idle
which is called too early for the fitBounds
method, the event tilesloaded
actually gets the job done (only called once)!
Solution:
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
var bounds = //define bounds...
map.fitBounds(bounds);
});