我想要在地图外有一个按钮,将视图更改为另一个坐标。
有没有办法让mapContainer实例调用它们的函数?或者说如何实现这个功能呢?
我尝试使用 ref 来获取它,但它不起作用。
这是我当前的代码
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
您需要使用一个包含您的按钮的组件。要获取地图实例,请使用whenCreated
的支柱MapContainer
。我认为mapRef
对于最新版本不再有效。
地图容器:
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
....
创建带有按钮及其事件的组件
function FlyToButton() {
const onClick = () => map.flyTo(regionCoord, zoom);
return <button onClick={onClick}>Add marker on click</button>;
}
Demo https://codesandbox.io/s/react-leaflet-v3x-get-map-instance-in-functional-component-hn0x4?file=/src/Map.jsx:1198-1224
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)