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:
draggable
prop or onChange
. 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;
}}
/>
componentDidUpdate
as I have the state that changes when the polygon is created (I am using lodash
). I am usign mousedown
and not onmousedown
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!
I found the solution! I changed a bit the part inside the componentDidUpdate
method:
componentDidUpdate(prevProps, prevState) {
if (
!_.isEqual(prevState.closePolygon, this.state.closePolygon) &&
this.state.closePolygon
) {
// the polygon is created and closed
let element = document.getElementsByClassName("geo-polygon")[0];
// necessary to access the this keyword inside the callback
const that = this;
element.addEventListener("mouseup", function () {
const newLatLangs = [...that._polygon.current.leafletElement._latlngs];
that.setState({ polygonCoordinatesAfterMoving: [...newLatLangs] });
});
}
}
Now the polygon gets correctly dragged inside the map (as it did before), but I can also save the new coordinates. I am saving them in a new variable as I have yet to optimize this solution, and I don't need to redraw a new polygon on the map with the new coordinates - the draggable={true}
Polygon
prop works just fine for me.
So, it seemed like I was almost there.
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.