Search code examples
angulartypescriptopenlayers

Change opacity of style icon's in the openlayer maps in Angular 16+


I need to change the style icons in the Feature added to the openlayers map (using latest openlayers version). I am using single layer only so I cannot apply the opacity in the layer. I have multiple points plotted with different coordinates with icons and now I need to change the opacity of the icons other than the selected feature.

Below is my function to assign the style icon in map layer.

const geometry = feature.getGeometry();
if (geometry && geometry.getType() === 'Point') {
return new Style({
      image: new Icon({
        anchor: [0.5, 0.5],
        src: `./assets/icons/ic-${feature.values_.status}.img`,
      }),
    });
}

With the select interaction I want to reduce the opacity of the other icons expect selected.

here is my select event handler from map.

this.map.addInteraction(this.select);
this.select.on('select', function (e) {
if(e.selected.length) {
 const selectmark = e.selected as Feature[];
 mymaplayer.setStyle(feature=> {
   console.log(feature);
 });
}

I planned to get the style from layer and to update it but I couldn't perform it. Also tried to set the style using setStyle function but couldn't achieve it as well. Any simpler way to perform this?


Solution

  • Use a Select interaction with null style, a vector layer with a style function which checks if any features are selected, and if they include the one being styled. Fire a change on the layer when the selection is changed.

    const select = new Select({style: null});
    
    const vectorLayer = new VectorLayer({
      source: vectorSource,
      style: function (feature) {
        const selectedFeatures = select.getFeatures().getArray();
        const opacity =
          selectedFeatures.length === 0 || selectedFeatures.includes(feature)
            ? 1
            : 0.5;
        iconStyle.getImage().setOpacity(opacity);
        return iconStyle;
      },
    });
    
    select.on('select', function () {
      vectorLayer.changed();
    });
    

    Working example https://codesandbox.io/s/icon-color-forked-7vx7j2?file=/main.js