首页 > 解决方案 > 使用 React-Leaflet 拖动后无法访问多边形坐标

问题描述

Polygon成功将 a 拖到地图上的其他位置后,我需要访问它的新坐标。我正在使用 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. draggableprop 或中访问坐标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)。我是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地图内正确移动,但我不知道如何访问它的新坐标(位置)。谢谢您的帮助!

标签: javascriptreactjsleafletreact-leaflet

解决方案


我找到了解决方案!我对方法内部的部分进行了一些更改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道具对我来说很好。

所以,我好像快到了。


推荐阅读