javascript - 使用 React-Leaflet 拖动后无法访问多边形坐标
问题描述
Polygon
成功将 a 拖到地图上的其他位置后,我需要访问它的新坐标。我正在使用 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
prop 或中访问坐标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
)。我是usignmousedown
而不是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
道具对我来说很好。
所以,我好像快到了。
推荐阅读
- c++ - 在不锁定 Mutex 的情况下读取受 Mutex 保护的共享数据
- c# - 通过list c#同时检查多个字符串
- python - 如何使用多线程使此代码更快
- typescript - Typescript:为类型别名创建扩展方法
- python - 在循环中将值添加到行并在数据框中连接
- java - spring-data-jpa 多对多 findByID
- javascript - webpack/babel 转译删除对象键
- python - 问题 Virtualenv
- parallel-processing - MPI_Bcast() 之前的障碍?
- unity3d - 在 URP 中投射透明平面的阴影