从打字稿文件中的“react-leaflet"将“onClick"功能添加到 MapContainer [英] Adding 'onClick' function to a MapContainer from 'react-leaflet' in typescript file
问题描述
在 Typescript 文件中,我无法从 'react-leaflet' 导入 'Map' 并使用 'MapContainer' 轻松修复它.但是,我需要为其添加一个onClick"功能,但MapContainer"不支持onClick".我遵循了文档,但它导致我遇到了新的/其他问题......我只需要添加一个简单的 onClick 函数,以使用户能够在此类地图上通过鼠标单击来标记位置.有谁知道一个简单的快速修复方法?
In a Typescript file, I can t import 'Map' from 'react-leaflet' and easily fixed it with 'MapContainer'. However, I need to add an 'onClick' function to it, but 'MapContainer' does not support 'onClick'. I followed the documentation but it led me to new/additional issues... I just need to add a simple onClick function to enable user mark a location with a mouseclick on such map. Anyone knows a simple quick fix?
推荐答案
对于那些仍在为此苦苦挣扎的人,我刚刚设法在 MAP 中捕获 CLICK EVENT 并(例如,在此处添加标记).如果您也需要它,我还会添加地理定位示例,所以:
For those who are still struggling with this, I've just managed to capture that CLICK EVENT IN MAP and (for example, add a marker there). I'm also adding the geolocation example in case you need it too, so:
- 创建一个功能组件来处理将发生事件的层(在我的例子中,该标记也会被打印出来).
- 在 MapContainer 中实例化该 func 组件.
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';
const SomeComponent = () => {
const [initialPosition, setInitialPosition] = useState<[number, number]>([0,0]);
const [selectedPosition, setSelectedPosition] = useState<[number, number]>([0,0]);
useEffect(() => {
navigator.geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords;
setInitialPosition([latitude, longitude]);
});
}, []);
...
const Markers = () => {
const map = useMapEvents({
click(e) {
setSelectedPosition([
e.latlng.lat,
e.latlng.lng
]);
},
})
return (
selectedPosition ?
<Marker
key={selectedPosition[0]}
position={selectedPosition}
interactive={false}
/>
: null
)
}
...
return(
<MapContainer
center={selectedPosition || initialPosition}
zoom={12}
>
<Markers />
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
)
}
这篇关于从打字稿文件中的“react-leaflet"将“onClick"功能添加到 MapContainer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!