Andrew De Andrade Andrew De Andrade - 2 months ago 18x
Javascript Question

Using setZoom() after using fitBounds() with Google Maps API V3

I'm using fitBounds() to set the zoom level on my map too include all the markers currently displayed. However, when I have only one marker visible, the zoom level is 100% (... which zoom level 20 I think...). However, I don't want it to be that far zoomed in so the user can adjust the position of the marker without having to zoom out.

I have the following code:

var marker =, this.markerNumber);;;;
if (this.markerNumber === 1) {;

where was previously defined as: = new google.maps.LatLngBounds();

However, the problem I am having is that the line;
doesn't work if I use;
, however, I know that line of code is correct because when I comment out the fitBound() line, the setZoom() magically starts functioning.

Any ideas how I resolve this? I'm thinking of setting a maxZoom level as an alternative if I can't get this working.


Alright, I've figured it out. Apparently, the fitbounds() happens asynchronously, so you have to wait for a bounds_changed event before setting zoom works.

map =;

zoomChangeBoundsListener = 
    google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
        if (this.getZoom()){
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);

Update: See @Nequin's answer using addListenerOnce for a better solution that doesn't require a timeout.