Skip to content
Advertisement

How to Set Leaflet Map’s Zoom to Show All Markers in React Leaflet?

I have a React Leaflet map that needs to change its center and zoom when given a set of markers. The zoom should be changed such that all the markers are visible.

This change of view is currently being attempted using the function ChangeView.

Using my code below, I am able to move the map view, but not able to let the map fit to the bounds. Running the code gives the error:

Error: Bounds are not valid.

on the line

JavaScript

What can we do? Thanks!

JavaScript

Also tried using FeatureGroup instead of latLngBounds, but it gave the exact same error

Error: Bounds are not valid

JavaScript

Advertisement

Answer

If the markers array is empty, or null, the bounds you create will not have ._southWest and ._northEast properties, and that error will throw. Just make the fitBounds statement conditional on there being markers in the array:

JavaScript

Or even just a quick one liner:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement