[英]How to add onClick to the map `leaflet`
I'm using Leaflet
i want to show an alert that shows latlng
of the clicked location I followed document steps in here https://leafletjs.com/examples/quick-start/我正在使用Leaflet
我想显示一个警报,显示单击位置的纬度 我按照此处的文档步骤latlng
://leafletjs.com/examples/quick-start/
I've tried this我试过这个
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
function onMapClick(e) { //THE FUNCTION
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
and at <MapContainer>
i defined it like在<MapContainer>
我将它定义为
<MapContainer id="mapid" onClick={onMapClick}/>
but it shows nothing但它什么也没显示
here is the whole code这是整个代码
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import React, { Component } from 'react';
import L from 'leaflet'
class UserMap extends Component {
render() {
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
return (
<div
id="mapid" style={{ height: '100%', width: '100%' }}>
<MapContainer
id="mapid"
center={[30.794900, 50.564580]}
zoom={13}
zoomOffset={1}
boxZoom={false}
scrollWheelZoom={true}
style={{ height: '500px', width: '100%' }}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={[30.794900, 50.564580]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer></div>
);
}
}
export default UserMap;
onClick
is not working anymore, instead you should use the useMapEvents
hook ( https://react-leaflet.js.org/docs/api-map/#usemapevents ). onClick
不再工作,您应该使用useMapEvents
挂钩( https://react-leaflet.js.org/docs/api-map/#usemapevents )。
Basically, you have to create a component with the useMapEvents
hook which will listen to the click and call this component in your MapContainer
.基本上,您必须使用useMapEvents
挂钩创建一个组件,该挂钩将监听点击并在您的MapContainer
中调用该组件。
Add the following code inside your MapContainer
to fix your issue:在MapContainer
中添加以下代码以解决您的问题:
function MyComponent() {
useMapEvents({
click(e){
alert(e.latlng)
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.