javascript - Leaflet React在功能组件中获取地图实例
问题描述
我想在地图外有一个按钮,将视图更改为另一个坐标。
有没有办法让 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>;
}
推荐阅读
- python - 如何在正则表达式中给出积极的范围
- python - 如果大于或等于 3 NaN (null),则删除行
- symfony - Symfony 将错误的默认值传递给参数
- javascript - 从具有给定 ID 的子数组中获取值
- java - 如何在 for 循环中增加 TextView 的大小并获取它的宽度,Android
- sql - 如何在没有重复列的情况下进行左连接?
- ace-editor - 更改 Ace 编辑器的默认键绑定
- php - 安装 Laravel reCaptcha 时未定义的变量 $configuration
- xml - XML 标记替换
- flutter - 返回地图时 FutureBuilder 中的空快照