OpenLayers – How to Get Properties of Highlighted Features When De-Highlighting

angularfeaturesopenlayers

this.map.on('singleclick', event => {
    const feature = this.map.forEachFeatureAtPixel(event.pixel, (feature) => {
      console.log(feature);
     return feature
    })
    if(feature instanceof Feature){
      alert(feature.getProperties().JBA_ASSET_ID);
      this.map.getView().fit(feature.getGeometry(),{"maxZoom":27} );
      var fill = new Fill({color: 'blue'});
      var stroke = new Stroke({color: 'red',width: 8});
      var styleNew = new Style({ fill,stroke});         
      feature.setStyle(styleNew)
    }
 }

 this.map.on('dblclick', event => {
  const feature = this.map.forEachFeatureAtPixel(event.pixel, (feature) => {
    console.log(feature);
    return feature
  })
  if(feature instanceof Feature){
    this.map.getView().fit(feature.getGeometry().getExtent(),{"maxZoom":17} );
    var styleNew=undefined      
    feature.setStyle(styleNew)
  }
}

From above code when I perform click operation on some features they will be get highlighted. If I perform the double click operation on the highlighted feature it has to be de-highlighted. Now I have to get the properties of the remaining highlighted features. Is it possible?

Best Answer

To have list of selected features you can create additional vector source selectedFeatures where you add selected feature and remove it, when it's unselected.

Relevant code could then look something like this (tested, plain JS, since I'm not familiar with Angular):

var selectedFeatures = new ol.source.Vector();

var fill = new ol.style.Fill({color: 'blue'});
var stroke = new ol.style.Stroke({color: 'red', width: 8});
var styleNew = new ol.style.Style({fill, stroke});         

map.on('singleclick', event => {
  const feature = this.map.forEachFeatureAtPixel(event.pixel, (feature) => {
    return feature;
  })
  if(feature instanceof ol.Feature){
    if (!selectedFeatures.hasFeature(feature)) {
      feature.setStyle(styleNew);
      selectedFeatures.addFeature(feature);
    }
  }
});

map.on('dblclick', event => {
  event.preventDefault();
  const feature = this.map.forEachFeatureAtPixel(event.pixel, (feature) => {
    return feature;
  })
  if(feature instanceof ol.Feature){
    if (selectedFeatures.hasFeature(feature)) {
      feature.setStyle();
      selectedFeatures.removeFeature(feature);
      var selectedList = '';
      selectedFeatures.forEachFeature(feature => {
        selectedList += feature.getProperties().JBA_ASSET_ID + ' ';
      });
      console.log('Still selected: ' + selectedList);
    }
  }
});