使用Reaction-Leaplet-Draw in Lamlet创建新图层之前删除图层

我这里的目的是在地图上只允许一个多边形。我的方法是在onCreated方法期间将新图层保存在变量或数组中,并在onDrawStart获取并删除方法中保存,所以一旦用户尝试绘制另一个形状,前一个将被移除,但这不起作用,有什么建议如何实现这一点吗?

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

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

是否有任何方法可以访问onDelete并访问此处的内置全部删除??


解决方案

您可以通过使用featureGroupRef检查存储的绘制层数来实现此目的。如果数字大于1,则删除先前存储的图层,只保留最新的图层。代码如下:

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

相关文章