Reputation: 19
I have been struggling with an issue which comes down to me not being able to properly reference the map object. After researching it for a few days, I've come to the conclusion that the "old" (up to v3.x) whenCreated prop of the MapContainer, which returned the Leaflet.Map object, has been removed.
Now all that's left is the whenReady prop, which is defined as () => void
. Therefore I am struggling to access the map object, which I desperately need.
Does anyone have any tips for this?
Upvotes: 1
Views: 1045
Reputation: 6163
The release notes for React Leaflet v4 state:
Removed
whenCreated
property from theMapContainer
component (aref
callback can be used instead).
What you can do is define a state to store a reference to the map:
const [map, setMap] = useState(null);
then when you create your MapContainer
get a reference to the map:
<MapContainer
center={[52.4498, -1.6]}
zoom={12}
scrollWheelZoom={false}
ref={setMap}
>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
then define a useEffect
where you can access the map
object:
useEffect(() => {
if (map) {
map.on('click', (e) => {
map.setZoom(8);
});
}
}, [map]);
There's a StackBlitz here to demonstrate this. If you click anywhere on the map, the code above will execute and set the zoom level to 8.
Upvotes: 3