[英]Can't access Polygon coordinates after drag with React-Leaflet
成功將Polygon
拖到地圖上的其他位置后,我需要訪問Polygon
的新坐標。 我正在使用 Leaflet 和 React-Leaflet。 這是我的多邊形組件:
<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>
我試過了:
draggable
道具或onChange
的坐標。 不用說,這不起作用: <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
因為我的狀態會在創建多邊形時發生變化(我正在使用lodash
)。 我使用的是mousedown
而不是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);
};
最后一種方法不起作用,因為它只觸發一次事件,就在我創建Polygon
,然后當我拖動它然后釋放鼠標時不會再次觸發。
TL;DR: Polygon
在地圖內正確移動,但我不知道如何訪問它的新坐標(位置)。 感謝您的幫助!
我找到了解決方案! 我稍微改變了componentDidUpdate
方法中的componentDidUpdate
:
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] });
});
}
}
現在多邊形被正確拖動到地圖內(就像以前一樣),但我也可以保存新坐標。 我將它們保存在一個新變量中,因為我還沒有優化這個解決方案,而且我不需要用新坐標在地圖上重新繪制一個新多邊形 - draggable={true}
Polygon
道具對我來說很好用。
所以,我好像快到了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.