1

我在这个问题中使用了解决方案(在使用传单中的 react-leaflet-draw 创建新图层之前删除图层)以获得在 React 和 Typescript 地图项目中仅绘制一个形状(图层)的能力,但是我得到了cannot read propery leafletElement of undefined,我使用了传单 v1 .7.1、leaflet-draw 1.0.4、React-leaflet v2.8.3 和 React-leaflet-draw v0.19.8,我猜 LeafletElement 在新版本中被替换为替代品。在以上版本中创建新形状时,如何实现删除图层?

注意 1:我<MapContainer/>在 React-leaflet v2.8.3 中使用了组件,它是<Map />React-leaflet v2.6.0 中的组件的替代品

注意2:我无法弄清楚editableFGe(在onCreated eventHandlerreactFGref中)和传单核心API的类型是什么,所以我使用了any

这是我的代码:

const [editableFG, setEditableFG] = useState<any>(null);

const onCreated = (e: any) => {
  const drawnItems = editableFG.leafletElement._layers;
  if (Object.keys(drawnItems).length > 1) {
    Object.keys(drawnItems).forEach((layerid, index) => {
    if (index > 0) {
      return;
    }
      const layer = drawnItems[layerid];
      editableFG.leafletElement.removeLayer(layer);
    });
  }
};

const onFeatureGroupReady = (reactFGref: any) => {
  setEditableFG(reactFGref);
};

return (
  <MapContainer
    center={center}
    zoom={zoom}
    className={classes.mapContainer}
  >
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
    />
    <FeatureGroup
      ref={
        (featureGroupRef: any) => {
          onFeatureGroupReady(featureGroupRef);
        }
      }
    >
      <EditControl
        position="topright" 
        onCreated={onCreated}
        draw={{
          rectangle: false,
          circleMarker: false,
          marker: false,
          circle: true,
          polyline: true,
          polygon: true
        }}
      />
    </FeatureGroup>
  </Map>
);
4

0 回答 0