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

如何限制图层中的多边形数量,每次新建时自动清除之前的矢量要素

实现方案

给OpenLayers的Draw交互绑定绘制事件,触发时清空已有矢量要素即可,以下是可直接运行的修改后代码:

let drawSource = new VectorSource({wrapX: false}); 

let drawLayer = new VectorLayer({source : drawSource,})
this.map.addLayer(drawLayer);

let draw = new Draw({
  source : drawSource,
  type : GeometryType.POLYGON,
  style : new Style({
    stroke: new Stroke({
          color: "#f00",
          width: 1,
        }),
    fill: new Fill({
      color: "#300",
    })
  })
});

// 新增逻辑:每次开始绘制新多边形前清空旧要素
draw.on('drawstart', () => {
  drawSource.clear()
})

this.map.addInteraction(draw)
可选调整逻辑

如果你需要等新多边形绘制完成后再删除旧要素,可以用drawend事件实现:

draw.on('drawend', (event) => {
  const newFeature = event.feature
  // 遍历删除所有非本次绘制的旧要素
  drawSource.getFeatures().forEach(feature => {
    if (feature !== newFeature) {
      drawSource.removeFeature(feature)
    }
  })
})

内容的提问来源于stack exchange,提问作者Kuro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:39:02