OpenLayers绘制新多边形时如何清除之前的多边形选择高亮?
你当前代码的问题在于每次触发选中逻辑时,都会创建新的矢量图层添加到地图中,从未清理历史创建的高亮图层,因此会出现多次选中的高亮叠加的情况。
优化方案不需要每次选中都新建图层,复用同一个高亮图层即可,仅对该图层的数据源做清空、新增要素的操作,修改后的代码如下:
const ghostDataLayer = new ol.layer.Vector(.... let drawingSource = new ol.source.Vector({useSpatialIndex: false}); // 全局声明唯一的高亮图层,仅初始化一次 const selectedSource = new ol.source.Vector() const selectedLayer = new ol.layer.Vector({ source: selectedSource, style: selectedPolygonStyle, zIndex: 99, }) map.addLayer(selectedLayer) let draw; draw = new ol.interaction.Draw({ type: 'Polygon', source: drawingSource, style: style }); map.addInteraction(draw); function highlightSelection(drawnPolygon) { ghostDataLayer.getSource().forEachFeatureIntersectingExtent(drawnPolygon, function(feature) { selectedFeatureCoordinates = feature.getGeometry().getCoordinates(); const selectedGeometry = new ol.geom.MultiPolygon(selectedFeatureCoordinates); const selectedPolygonFeature = new ol.Feature({ geometry: selectedGeometry }); // 直接往已有的高亮数据源加要素,不用新建图层 selectedSource.addFeature(selectedPolygonFeature) }); }; draw.on('drawstart', function(event){ drawingSource.clear(); // 开始绘制新多边形时,清空之前的高亮要素 selectedSource.clear() }, this); draw.on('drawend', function(event) { let drawnPolygonExtent = event.feature.getGeometry().getExtent(); highlightSelection(drawnPolygonExtent); });
如果你确实需要每次选中都生成独立图层的场景,也可以用一个数组存储所有创建过的高亮图层,在drawstart触发时遍历数组调用map.removeLayer()逐个移除,再清空数组即可,不过复用单图层的方案性能更高。
内容的提问来源于stack exchange,提问作者MaxDragonheart
相关产品推荐
相关产品推荐

