[英]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.