如何解决使用React-Leaflet拖动后无法访问多边形坐标
在成功将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(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
道具可以正常工作对我很好。
所以,好像我快到了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。