問(wèn)題描述
我想在地圖外有一個(gè)按鈕,可以將視圖更改為另一個(gè)坐標(biāo).
I want to have a button outside the map that changes the view to another coordinates.
有沒(méi)有辦法讓 mapContainer 實(shí)例調(diào)用它們的函數(shù)?或者我該如何實(shí)現(xiàn)這個(gè)功能?
Is there any way to get mapContainer instance to call their functions? Or how can I implement that function?
我試圖通過(guò)使用 ref 來(lái)獲取它,但它不起作用.這是我當(dāng)前的代碼
I tried to get it by using ref, but it's not working. Here is my current code
const zoom = 13;
function Map({ regionCoord, regionName }) {
const mapRef = useRef();
function handleFlyToClick() {
// This don't work
// const map = mapRef.current.leafletElement
// map.flyTo(regionCoord, zoom)
}
return (
<React.Fragment>
<Grid container >
<Grid item xs={10}>
{regionCoord && <MapContainer
ref={mapRef}
center={[50,50]}
zoom={zoom}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={regionCoord}>
<Popup>{regionName}</Popup>
</Marker>
</MapContainer>}
</Grid>
<Grid item xs={2}>
<button onClick={handleFlyToClick}>Fly To</button>
</Grid>
</Grid>
</React.Fragment>
)
}
export default Map
我正在使用 react-leaflet v3
I'm using react-leaflet v3
推薦答案
你需要使用一個(gè)包含你的按鈕的組件.要獲取地圖實(shí)例,請(qǐng)使用 MapContainer
的 whenCreated
屬性.我認(rèn)為 mapRef
在最新版本中不再有效.
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.
地圖容器:
const [map, setMap] = useState(null);
<MapContainer
center={[50, 50]}
zoom={zoom}
style={{ height: "90vh" }}
whenCreated={setMap}
>
...
</MapContainer>
<FlyToButton /> // use the button here outside of the MapContainer
....
使用按鈕及其事件創(chuàng)建組件
Create the component with the button and its event
function FlyToButton() {
const onClick = () => map.flyTo(regionCoord, zoom);
return <button onClick={onClick}>Add marker on click</button>;
}
演示
這篇關(guān)于Leaflet React在功能組件中獲取地圖實(shí)例的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!