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/
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 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 ).
Basically, you have to create a component with the useMapEvents
hook which will listen to the click and call this component in your MapContainer
.
Add the following code inside your MapContainer
to fix your issue:
function MyComponent() {
useMapEvents({
click(e){
alert(e.latlng)
}
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.