使用 React-Leaflet 拖动后无法访问多边形坐标

Can't access Polygon coordinates after drag with React-Leaflet

在我成功将它拖到地图上的其他地方后,我需要访问 Polygon 的新坐标。我正在使用 Leaflet 和 React-Leaflet。 这是我的多边形组件:

 <Map
  // ...
 >
   <TileLayer
     attribution='&copy; <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>

我试过了:

  1. 访问 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;
    }}
 />
  1. 要使用 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 道具可以正常工作对我来说很好。

所以,我好像快到了。