I'm trying to update the latitude and longitude coordinates after dragging a Marker over an Leaflet map in my React project. This is my map container component:
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import './styles/Map.css';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
//import {MarkerIcon} from './Icon.js';
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';
let DefaultIcon = L.icon({
iconUrl: icon,
shadowUrl: iconShadow
});
L.Marker.prototype.options.icon = DefaultIcon;
class Mapa extends React.Component{
constructor(props) {
super(props);
this.state = {
currentLocation: { lat: -16.399, lng: -71.536 },
zoom: 17,
}
this.updatePosition = this.updatePosition.bind(this);
}
updatePosition = (e) =>{
e.preventDefault();
console.log("hola");
/*this.setState({currentLocation:e.latlng})*/
};
render() {
return (
<MapContainer center={this.state.currentLocation} zoom={this.state.zoom}>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution="© <a href='https://osm.org/copyright'>OpenStreetMap</a> contributors" />
<Marker position={this.state.currentLocation} draggable={true} onDragend={this.updatePosition}>
<Popup>{"Latitud: "+this.state.currentLocation.lat}<br /> {"Longitud: "+this.state.currentLocation.lng}</Popup>
</Marker>
</MapContainer>
);
}
}
export default Mapa;
However nothing happened after dragging the Marker, i've tried to change the name of the event, but none is shown on console. Everything else is working fine. Any ideas?
onDragend
method available on Marker in version 3. You need to use a functional component to make it work usingeventHandlers