如何限制图层中的多边形数量,每次新建时自动清除之前的矢量要素
实现方案
给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
相关产品推荐
相关产品推荐

