Search code examples
javascriptgoogle-mapsgoogle-maps-api-3fitbounds

Google Maps v3: Enforcing min. zoom level when using fitBounds


I'm drawing a series of markers on a map (using v3 of the maps api).

In v2, I had the following code:

  bounds = new GLatLngBounds();

  ... loop thru and put markers on map ...
  bounds.extend(point);
  ... end looping

  map.setCenter(bounds.getCenter());
  var level = map.getBoundsZoomLevel(bounds);
  if ( level == 1 ) 
    level = 5;
  map.setZoom(level > 6 ? 6 : level);

And that work fine to ensure that there was always an appropriate level of detail displayed on the map.

I'm trying to duplicate this functionality in v3, but the setZoom and fitBounds don't seem to be cooperating:

... loop thru and put markers on the map
  var ll = new google.maps.LatLng(p.lat,p.lng);
  bounds.extend(ll);
... end loop

var zoom = map.getZoom();
map.setZoom(zoom > 6 ? 6 : zoom);
map.fitBounds(bounds);

I've tried different permutation (moving the fitBounds before the setZoom, for example) but nothing I do with setZoom seems to affect the map. Am I missing something? Is there a way to do this?


Solution

  • At this discussion on Google Groups I discovered that basically when you do a fitBounds, the zoom happens asynchronously so you need to capture the zoom and bounds change event. The code in the final post worked for me with a small modification... as it stands it stops you zooming greater than 15 completely, so used the idea from the fourth post to have a flag set to only do it the first time.

    // Do other stuff to set up map
    var map = new google.maps.Map(mapElement, myOptions);
    // This is needed to set the zoom after fitbounds, 
    google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener = 
            google.maps.event.addListener(map, 'bounds_changed', function(event) {
                if (this.getZoom() > 15 && this.initialZoom == true) {
                    // Change max/min zoom here
                    this.setZoom(15);
                    this.initialZoom = false;
                }
            google.maps.event.removeListener(zoomChangeBoundsListener);
        });
    });
    map.initialZoom = true;
    map.fitBounds(bounds);
    

    Anthony.

    Update April 2023:

    Per the comments below, using modern JS and Google Maps API V3, this block should look something like:

    map = new google.maps.Map(mapElement, myOptions);
    map.maxDefaultZoom = 15;
    
    google.maps.event.addListenerOnce(map, "bounds_changed", function () {
      this.setZoom(Math.min(this.getZoom(), this.maxDefaultZoom));
    });