Google Maps API v3: Can I setZoom after fitBounds?

前端 未结 23 2487
执笔经年
执笔经年 2020-11-27 09:35

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

23条回答
  •  死守一世寂寞
    2020-11-27 09:42

    I saw many incorrect or too complicated solutions, so decided to post a working, elegant solution.

    The reason setZoom() doesn't work as you expect is that fitBounds() is asynchronous, so it gives no guarantee that it would immediately update the zoom, but your call to setZoom() relies on that.

    What you might consider is setting the minZoom map option before calling fitBounds() and then clearing it after it completes (so that users can still zoom out manually if they want to):

    var bounds = new google.maps.LatLngBounds();
    // ... (extend bounds with all points you want to fit)
    
    // Ensure the map does not get too zoomed out when fitting the bounds.
    gmap.setOptions({minZoom: 6});
    // Clear the minZoom only after the map fits the bounds (note that
    // fitBounds() is asynchronous). The 'idle' event fires when the map
    // becomes idle after panning or zooming.
    google.maps.event.addListenerOnce(gmap, 'idle', function() {
      gmap.setOptions({minZoom: null});
    });
    
    gmap.fitBounds(bounds);
    

    In addition, if you want to also limit the max zoom, you can apply the same trick with the maxZoom property.

    See the MapOptions docs.

提交回复
热议问题