Delete layer before creating a new one with react-leaflet-draw in leaflet(使用Reaction-Leaplet-Draw in Lamlet创建新图层之前删除图层)
                            本文介绍了使用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='© <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
这篇关于使用Reaction-Leaplet-Draw in Lamlet创建新图层之前删除图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:使用Reaction-Leaplet-Draw in Lamlet创建新图层之前删除图层
				
        
 
            
        
             猜你喜欢
        
	     - 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
 - 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
 - 为什么我的页面无法在 Github 上加载? 2022-01-01
 - 在不使用循环的情况下查找数字数组中的一项 2022-01-01
 - 如何显示带有换行符的文本标签? 2022-01-01
 - 从原点悬停时触发 translateY() 2022-01-01
 - 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
 - 如何向 ipc 渲染器发送添加回调 2022-01-01
 - 如何调试 CSS/Javascript 悬停问题 2022-01-01
 - 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
 
						
						
						
						
						
				
				
				
				