Search code examples
javascriptopenlayers

How to remove style from individual feature of a Vector Layer in Open Layers?


I'm learning the OpenLayers library of JS. I have successfully set a click event to change the style of an individual feature. However, I want to remove the style once I have clicked somewhere else or on to other feature.

var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;

// Basic Style for the point layer
const pointStyle = new ol.style.Style({
    image: new ol.style.Circle({
        radius: width * 2,
        fill: new ol.style.Fill({
            color: blue
        }),
    }),
})
const map = new ol.Map({
    //Some Parameters
})

const points = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: './res/points.json',
        format: new ol.format.GeoJSON(),
    }),
    style: pointStyle,
    title: 'Points'
})

const myLayerGroup = new ol.layer.Group({
    layers: [boundary, points]
})
map.addLayer(myLayerGroup);

map.on('click', function(e) {
    map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
        if (feature.get('Name')) {
            if (feature.getStyle() == null) {
                layer.setStyle(pointStyle);
                feature.setStyle(); //Tried setting style to null here, didn't work
                feature.setStyle(new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: width * 2,
                        fill: new ol.style.Fill({
                            color: white //Basically points change to white here
                        }),
                    })
                }))
            }
        }
    })
})

I seems once I have set a style to individual element, even if I overwrite the style of whole layer, the style of the individual element still persists. I haven't found a method to loop over each feature and set their individual styles to be blank.


Solution

  • You can use a variable to record which feature was changed

    let changedFeature;
    map.on('click', function(e) {
        if (changedFeature)
            changedFeature.setStyle();
            changedFeature = undefined;
        }
        map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
            if (feature.get('Name')) {
                if (feature.getStyle() == null) {
                    feature.setStyle(new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: width * 2,
                            fill: new ol.style.Fill({
                                color: white //Basically points change to white here
                            }),
                        })
                    }))
                    changedFeature = feature;
                }
            }
        })
    })