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创建新图层之前删除图层
基础教程推荐
猜你喜欢
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01