Reputation: 7199
I am using react-leaflet for showing non-geographical map.
I also added some event for zoom changing. (onZoomEnd()
)
I wonder how to access map object or map component and get current zoom level. Or other maps props?
<Map
center={this.getCalculatedCenterFromState()}
zoom={this.getCalculatedZoomFromState()}
minZoom={this.getCalculatedMinZoomFromState()}
maxZoom={2}
onZoomEnd={this.mapService.handleZoomstart(/* map.object */)}
>
</Map
I need to access map object in handler method
handleZoomstart = (map) => {
// TODO handle move event
};
Upvotes: 1
Views: 21754
Reputation: 71
Solutions under didn't work for me. If you use react-leaflet v3 you can use this. One note, hook useMapEvents you need call from children component "MapContainer" it's impotant!
import {useMapEvents} from "react-leaflet";
import {useState} from "react";
function MyComponent() {
const [zoomLevel, setZoomLevel] = useState(5); // initial zoom level provided for MapContainer
const mapEvents = useMapEvents({
zoomend: () => {
setZoomLevel(mapEvents.getZoom());
},
});
console.log(zoomLevel);
return null
}
function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={5}>
<MyComponent />
</MapContainer>
)
}
Upvotes: 7
Reputation: 11
I just solved the above problem quite simply. React leaflet provides a nice "onViewportChange" callback that captures center and zoom changes when using the map.
You need three things, the declared "Viewport" object, a function that supports callback and callback.
const viewport = {
center: [49.32707, 19.10041],
zoom: 5,
};
const onViewportChanged = (viewport) => {
console.log(viewport);
};
return (
<Map viewport={viewport} onViewportChanged={onViewportChanged}></Map>)
Best regards
Upvotes: 1
Reputation: 439
This can be alternatively done without using refs. Use the event 'onZoomEnd'.
This event object has '_zoom' property, which is current zoom state.
e.target._zoom
Upvotes: 1
Reputation: 2311
You need to add a reference to the map:
<Map
ref={(ref) => { this.map = ref; }}
{...}
>
(...)
</Map>
Then you can access the map:
handleZoomstart = (map) => {
console.log(this.map && this.map.leafletElement);
};
And the current zoom:
getMapZoom() {
return this.map && this.map.leafletElement.getZoom();
}
Upvotes: 8