I need to access the new coordinates of a Polygon after I have successfully dragged it somewhere else on the map. I am using Leaflet and React-Leaflet.
This is my Polygon component:
<Map
// ...
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<Polygon
positions={this.state.polygonCoordinates}
ref={this._polygon}
draggable={true}
/>
</Map>
I have tried:
- To access the coordinates either in the
draggableprop oronChange. Needless to say, this didn't work:
<Polygon
positions={this.state.polygonCoordinates}
ref={this._polygon}
onChange={(event) => {
console.log(event);
console.log(this._polygon.current.leafletElement);
}}
draggable={(event) => {
console.log(event);
console.log(this._polygon.current.leafletElement);
return true;
}}
/>
- To use
componentDidUpdateas I have the state that changes when the polygon is created (I am usinglodash). I am usignmousedownand notonmousedown
componentDidUpdate(prevProps, prevState) {
if (
!_.isEqual(prevState.closePolygon, this.state.closePolygon) &&
this.state.closePolygon
) {
// the polygon is created and closed
const leafletPolygon = this._polygon.current.leafletElement;
leafletPolygon.addEventListener("onmousedown", this.movePolygon(event));
}
}
movePolygon = (event) => {
console.log(event, this._polygon);
};
This last approach does not work because it fires the event only once, right after I create the Polygon, and then doesn't fire again when I drag it around and then release the mouse.
TL;DR: the Polygon is correctly moved inside the map, but I can't figure out how to access its new coordinates (positions).
Thank you for your help!