Leaflet React Get Map Instance In Functional Component
I want to have a button outside the map that changes the view to another coordinates. Is there any way to get mapContainer instance to call their functions? Or how can I implement
Solution 1:
You need to use a component which will include your button inside. To take the map instance use whenCreated
prop of MapContainer
. I think mapRef
is not valid anymore with the latest version.
MapContainer:
const [map, setMap] = useState(null);
<MapContainercenter={[50,50]}
zoom={zoom}style={{height: "90vh" }}
whenCreated={setMap}
>
...
</MapContainer><FlyToButton />// use the button here outside of the MapContainer
....
Create the component with the button and its event
functionFlyToButton() {
constonClick = () => map.flyTo(regionCoord, zoom);
return<buttononClick={onClick}>Add marker on click</button>;
}
Solution 2:
you need to access the map element(from the map component which is the container not MapContainer), this is a very simple example:
exportdefaultfunctionMapComponent() {
const [mapCenter,setMapCenter] = useState([13.1538432,30.2154278])
let [zoom,setZoomLevel] = useState(15)
let [tile,setTile] = useState('https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png')
let mapRef = useRef();
constfly=()=>{
mapRef.current.leafletElement.flyTo([14,30],15)
}
return (
<><buttononClick={fly}>Click</button><Mapcenter={mapCenter}zoom={zoom}ref={mapRef}style={{width:'100%',height:'100%'}}><TileLayerurl={tile}/></Map></>
)
}
Post a Comment for "Leaflet React Get Map Instance In Functional Component"