我有一个OpenLayers 4地图,它具有单击交互作用,并且具有用于“ select”事件的相应事件处理程序,该事件处理程序会更改所选要素样式。
let clickInteraction = new olInteractionSelect({
layers: function (layer: any) {
return layer.get('selectable') == true;
},
condition: olEventCondition.singleClick,
filter: (feature: any, layer: any) => {
let shouldReturn: boolean = false;
switch (layer.get(this.LAYER_PROPERTY_ID)) {
case this.LAYER_ID_POINTS:
this.onPointClick(feature.getId());
shouldReturn = true;
break;
case this.LAYER_ID_AREAS:
this.onAreaClick(feature.getId());
shouldReturn = true;
break;
default:
break;
}
return shouldReturn;
}
});
let __this = this;
clickInteraction.on('select', function (evt: any) {
let selected = evt.selected;
let deselected = evt.deselected;
//Select and set style for newly selected features
if (selected.length) {
selected.forEach(function (feature: any) {
if (feature.get(__this.FEATUREKEY_SELECTEDSTYLEID)) {
feature.setStyle(__this.createStyleFnFeatureSelected(feature.get(__this.FEATUREKEY_SELECTEDSTYLEID)));
}
});
} else {
deselected.forEach(function (feature: any) {
if (feature.get(__this.FEATUREKEY_STYLEID)) {
feature.setStyle(__this.createStyleFn(feature.get(__this.FEATUREKEY_STYLEID)));
}
});
}
});
this.map.addInteraction(clickInteraction);
每次选择一个新功能时,我都要设置所有先前选择的功能的样式。我不知道是什么时候调用了单击交互的“选择”事件,如何在地图层上获取所有先前选择的要素的集合?
地图上有数千个要素,因此从性能角度来看,对所有要素进行迭代是不可行的。我要实现的只是获取以前选择的功能,而不是当前单击交互事件中选择或取消选择的功能。
答案 0 :(得分:1)
您可以简单地维护所选要素的队列,并在选择新要素时将其添加到队列中。队列的处理可以是可选的,但必须在添加新功能之前完成
let prevSelection = [];
clickInteraction.on('select', function (evt: any) {
let selected = evt.selected;
let deselected = evt.deselected;
//Restyle previously selected features now if desired (or leave until next time)
if (myCondition) {
prevSelection.forEach(
...
)
prevSelection = [];
}
//Append newly selected features to queue for next time
prevSelection = prevSelection.concat(selected);
//Select and set style for newly selected features
if (selected.length) {