Categories
JavaScript Answers

How to enforce min. zoom level when using fitBounds with Google Maps v3 and JavaScript?

Spread the love

Sometimes, we want to enforce min. zoom level when using fitBounds with Google Maps v3 and JavaScript.

In this article, we’ll look at how to enforce min. zoom level when using fitBounds with Google Maps v3 and JavaScript.

How to enforce min. zoom level when using fitBounds with Google Maps v3 and JavaScript?

To enforce min. zoom level when using fitBounds with Google Maps v3 and JavaScript, we can set the minimum zoom level in the bounds_changed event handler.

For instance, we write

const zoomChangeBoundsListener = google.maps.event.addListener(
  map,
  "bounds_changed",
  (event) => {
    google.maps.event.removeListener(zoomChangeBoundsListener);
    map.setZoom(Math.min(15, map.getZoom()));
  }
);

map.fitBounds(zoomBounds);

to call addListener to listen to the bounds_changed event on the map.

In the event listener, we call map.setZoom to set the zoom level to 15 if the zoom level is below 15.

Otherwise, we use getZoom to return the zoom level and set that as the zoom level of the map.

Conclusion

To enforce min. zoom level when using fitBounds with Google Maps v3 and JavaScript, we can set the minimum zoom level in the bounds_changed event handler.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.