问题描述
在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?
推荐答案
对于那些仍在努力解决这个问题的人,我刚刚设法在地图上捕获了该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 {'react-leaflet'中的MapContainer,Marker,TileLayer,useMapEvents};
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>
)
}
顺便说一句,stackoverflow的[代码解析器]到底是怎么回事?
BTW what a hell is going on with the [code parser] of stackoverflow???
这篇关于从打字稿文件中的"react-leaflet"向MapContainer添加"onClick"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!