1

I used the solution in this question (Delete layer before creating a new one with react-leaflet-draw in leaflet) to gain ability to draw only one shape(layer) in React and Typescript map project, but I got cannot read propery leafletElement of undefined, I used leaflet v1.7.1, leaflet-draw 1.0.4, React-leaflet v2.8.3 and React-leaflet-draw v0.19.8, I guess leafletElement is replaced with something alternative in new versions. How can I implement deleting layers when new shape is created in versions above?

Note1: I used <MapContainer/> component in React-leaflet v2.8.3 which is alternative to <Map /> component in React-leaflet v2.6.0

Note2: I can't figure out what is type of editableFG and e (in onCreated eventHandler) and reactFGref in leaflet core API so I used any

Here is my code:

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>
);
  • Check my [suggestion](https://stackoverflow.com/a/74094165/14247395) in the linked question. – kibz Oct 20 '22 at 07:58

0 Answers0