You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:15:01