如何在OpenLayers中撤销或删除点交互绘制的点要素
解决方案
所有绘制完成的点要素均存储在你传入ol.interaction.Draw的矢量数据源source中,移除绘制交互不会影响已生成的要素,直接操作数据源即可实现删除需求。
1. 撤销最近绘制的点
直接删除数据源中最后插入的要素即可,代码示例:
const undoLastDraw = (vectorSource) => { const allFeatures = vectorSource.getFeatures(); if (allFeatures.length) { vectorSource.removeFeature(allFeatures.at(-1)); } }
将该方法绑定到撤销按钮的点击事件即可实现单次撤销,需要支持多步撤销可额外维护一个操作栈存储历史绘制要素。
2. 点击删除任意指定点
新增选中交互,监听点击选中事件后删除对应要素:
const initPointDelete = (map, vectorSource, pointLayer) => { // 初始化选中交互,仅命中绘制点所在的矢量图层 const selectInteraction = new ol.interaction.Select({ condition: ol.events.condition.click, layers: [pointLayer] // 替换为你存储绘制点的矢量图层实例 }); map.addInteraction(selectInteraction); // 选中后直接删除对应点 selectInteraction.on('select', (event) => { const selected = event.selected; if (selected.length) { vectorSource.removeFeature(selected[0]); selectInteraction.getFeatures().clear(); } }); }
初始化页面时调用上述方法即可,不需要和绘制交互耦合。
内容的提问来源于stack exchange,提问作者Jantoma21
相关产品推荐
相关产品推荐

