Google Maps API v3: Can I setZoom after fitBounds?

I have a set of points I want to plot on an embedded Google Map (API v3). I'd like the bounds to accommodate all points unless the zoom level is too low (i.e., zoomed out too much). My approach has been like this:

var bounds = new google.maps.LatLngBounds();

// extend bounds with each point

gmap.fitBounds(bounds); 
gmap.setZoom( Math.max(6, gmap.getZoom()) );

This doesn't work. The last line "gmap.setZoom()" doesn't change the zoom level of the map if called directly after fitBounds.

Is there a way to get the zoom level of a bounds without applying it to the map? Other ideas to solve this?


Edit: See Matt Diamond's comment below.

Got it! Try this:

map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() { 
  if (map.getZoom() > 16) map.setZoom(16); 
  google.maps.event.removeListener(listener); 
});

Modify to your needs.


I solved a similar problem in one of my apps. I was a little confused by your description of the problem, but I think you have the same goal I had...

In my app I wanted to plot a one or more markers and ensure the map was showing them all. The problem was, if I relied solely on the fitBounds method, then the zoom-level would be maxed out when there was a single point - that was no good.

The solution was to use fitBounds when there was many points, and setCenter+setZoom when there was only one point.

if (pointCount > 1) {
  map.fitBounds(mapBounds);
}
else if (pointCount == 1) {
  map.setCenter(mapBounds.getCenter());
  map.setZoom(14);
}

I have come to this page multiple times to get the answer, and while all the existing answers were super helpful, they did not solve my problem exactly.

google.maps.event.addListenerOnce(googleMap, 'zoom_changed', function() {
    var oldZoom = googleMap.getZoom();
    googleMap.setZoom(oldZoom - 1); //Or whatever
});

Basically I found that the 'zoom_changed' event prevented the UI of the map from "skipping" which happened when i waited for the 'idle' event.

Hope this helps somebody!


I’ve just fixed this by setting maxZoom in advance, then removing it afterwards. For example:

map.setOptions({ maxZoom: 15 });
map.fitBounds(bounds);
map.setOptions({ maxZoom: null });