0

My purpose here is to allow only one polygon on the map. My approach has been saving the new layer during onCreated method in a var or array and in the method onDrawStart get it and delete, so once the user tries to draw another shape, the previous one gets removed, but this is not working, any suggestion how to make it possible?

onCreated = (e) => {
  coordinates = e.layer._bounds;
  layer.push(e.layer);
}

onDrawStart = (e) => {
  layer.forEach((ele) => {
    ele.remove()
  });
}

Is there maybe any way to access to onDelete and to access here to the built in remove all??

4

1 回答 1

2

You can achieve that by checking the stored drawn layers number using a featureGroupRef. If the number is bigger than one then delete the previous stored layer and only keep the latest one. Here is the code:

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

const onCreated = e => {
    console.log(e);
    console.log(editableFG);

    // here you have all the stored layers
    const drawnItems = editableFG.leafletElement._layers;
    console.log(drawnItems);
    // if the number of layers is bigger than 1 then delete the first
    if (Object.keys(drawnItems).length > 1) {
        Object.keys(drawnItems).forEach((layerid, index) => {
            if (index > 0) return;
            const layer = drawnItems[layerid];
            editableFG.leafletElement.removeLayer(layer);
        });
        console.log(drawnItems); // here you will get only the last one
    }
};

const onFeatureGroupReady = reactFGref => {
    // store the featureGroup ref for future access to content
    setEditableFG(reactFGref);
};

return (
    <Map
        center={[37.8189, -122.4786]}
        zoom={13}
        style={{ height: '100vh' }}>
        <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 => {
                onFeatureGroupReady(featureGroupRef);
            }}>
            <EditControl position="topright" onCreated={onCreated} />
        </FeatureGroup>
    </Map>
);

Demo

于 2020-04-09T07:40:33.637 回答