多层数据注入同一个图层源时,要批量删除某一种要素

问题:因为多种类型要素放入同一个源,在删除某一类要素时需要遍历整个图层源,符合条件后才执行

source.removeFeature(feature);

  这样后导致程序执行速度很慢。

解决方案:在将各类要素添加到source的同时,将所有要素都存入一个数组FeatureList[]中,在需要删除一类要素时,首先直接将source清空(source.clear()),再遍历该数组并将符合条件的数组元素在数组中删除,最后将数组剩余的要素添加到source中。

示例代码:

//添加要素 
for (var i = 0; i < obj.length; i++) { var coodinate = [Number(obj[i].lon), Number(obj[i].lat)]; var point = new ol.geom.Point(coodinate); //根据坐标生成要素点 var feature = new ol.Feature({ geometry: point, tablename: tablename, featureId: obj[i].id }); //设置样式 feature.setStyle(new ol.style.Style({ image: new ol.style.Icon({ anchor: [0.5, 30], anchorXUnits: 'fraction', anchorYUnits: 'pixels', src: icons[4] }), text: new ol.style.Text({ text: obj[i].name, font: '700 12px 微软雅黑', fill: new ol.style.Fill({ color: "#000" }), stroke: new ol.style.Stroke({ color: "rgb(253,252,252)", 0.5 }), offsetY: -35, }) })); features.push(feature);
//将各类要素同时加入到featureList
featureList.push(feature) 

}
//遍历删除要素
buliding_source.clear();
        for (var i = 0; i < featureList.length; i++) {
            if (featureList[i].N.tablename == tablename) {
                featureList.splice(i, 1);
                i--;
            }
        }
        buliding_source.addFeatures(featureList);






原文地址:https://www.cnblogs.com/weixiaoxiang/p/13139199.html