I’m using react-leaflet package to create bound animation on the map from selected markers as seen on the screenshot below.
Here is the full code: https://codesandbox.io/s/react-leaflet-marker-with-bound-869mj
The map will be bound if only the selected markers change.
I try to implement the bound animation sample code from the documentation here https://react-leaflet.js.org/docs/example-view-bounds/
As we can see from the screenshot above, the map, the markers, the rectangle, and the panel (top-right corner) are displaying and working fine.
But if we change the selected markers (through the panel), the bound animation is not working properly (not showing all of the markers).
And if we empty the selected markers (no marker is selected in the panel), the app crashes and produces an error Cannot read properties of undefined (reading 'lat')
.
So, my questions are:
- how could this happen?
- what is the solution?
Advertisement
Answer
Finally, I could do it after directly updating the newest value of bounds (location list) inside onCheckboxChange
function.
So the useEffect
hook with selectedPlaces
is not needed anymore.
const onCheckboxChange = (inputIndex) => { let newPlaces = [...selectedPlaces]; newPlaces[inputIndex].selected = !newPlaces[inputIndex].selected; setSelectedPlaces(newPlaces); let newBounds = selectedPlaces.filter((item) => item.selected); newBounds = newBounds.map((item) => item.location); setBounds(newBounds); map.fitBounds(newBounds); }; useEffect(() => { map.fitBounds(initialBounds); }, []);
Here is the working demo: https://codesandbox.io/s/learn-react-leaflet-cnk8tm