[英]react-leaflet get current latlng onClick
如果有人能帮助我,我会很高兴...我已经在我的 React 项目上安装了 react-leaflet,并且 map 组件已成功加载,我需要获取当前的 latlng 并在单击 map 时在弹出窗口中显示它但我不知道该怎么做:(
请...请...帮助我...
这是我的代码
import React from 'react'
import { Map as LeafletMap, TileLayer, Marker, Popup } from 'react-leaflet';
class Mapp extends React.Component {
componentDidMount() {
}
render() {
return (
<LeafletMap
center={[35.755229,51.304470]}
zoom={16}
maxZoom={20}
attributionControl={true}
zoomControl={true}
doubleClickZoom={true}
scrollWheelZoom={true}
dragging={true}
animate={true}
easeLinearity={0.35}
>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
<Marker position={[35.755229,51.304470]}
draggable={true}
>
<Popup >
Popup for any custom information.
</Popup>
</Marker>
</LeafletMap>
);
}
}
export default Mapp;
这是有关单击地图后如何在弹出窗口中显示制造商位置的示例:
class MapExample extends Component {
constructor(props) {
super(props);
this.state = {
currentPos: null
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
this.setState({ currentPos: e.latlng });
}
render() {
return (
<div>
<Map center={this.props.center} zoom={this.props.zoom} onClick={this.handleClick}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
{ this.state.currentPos && <Marker position={this.state.currentPos} draggable={true}>
<Popup position={this.state.currentPos}>
Current location: <pre>{JSON.stringify(this.state.currentPos, null, 2)}</pre>
</Popup>
</Marker>}
</Map>
</div>
)
}
}
说明:
currentPos
状态用于保持标记位置 event.latLng
财产Map.onClick
事件处理函数返回的鼠标事件位置 这是一个演示供您参考
如果你使用 react-leaflet 版本 3.x,这将不起作用。 在这种情况下,在您添加到 map 的虚拟组件中使用 useMapEvents 挂钩。例如,如果您想要控制台记录被点击的 position:
const LocationFinderDummy = () => {
const map = useMapEvents({
click(e) {
console.log(e.latlng);
},
});
return null;
};
然后使用map中的LocationFinderDummy如下:
<MapContainer
center={[0, 0]}
zoom={6}>
<LocationFinderDummy />
</MapContainer>
您尝试达到什么目的?
这将是开始:
使用LeafletMap组件中的click(请参阅https://leafletjs.com/reference-1.4.0.html#map-click )事件并调用您的函数,例如:
<LeafletMap
center={[35.755229,51.304470]}
zoom={16}
maxZoom={20}
attributionControl={true}
zoomControl={true}
doubleClickZoom={true}
scrollWheelZoom={true}
dragging={true}
animate={true}
easeLinearity={0.35}
onclick={this.handleClick}>
>
...
</LeafletMap>
在handleClick函数中,您将获得lat和lng的信息,如下所示:
handleClick = (e) => {
const { lat, lng } = e.latlng;
console.log(lat, lng);
}
从这里开始,您可以使用所需的信息创建标记/弹出窗口。
其他提示:请确保您的代码正确包装在帖子中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.