0

let's say I have a vector layer created from 2 features.

  • The vector layer has style set to green color.
  • There is a select interaction with a style set to red color (in other words, I want to click on a feature and make it turn red).
  • I set style of one of the features to blue color by calling feature.setStyle().

If I select the green feature, it shows up red. If I select the blue feature, it stays blue.

Is that correct behaviour?

Following is the code snippet:

const geojsonObject = {
    type: 'FeatureCollection',
    features: [
        {
            type: 'Feature',
            properties: {},
            geometry: {
                type: 'Polygon',
                coordinates: [
                    [ [10.0, 40.0], [15.0, 40.0], [15.0, 50.0], [10.0, 50.0], [10.0, 40.0] ]
                ]
            }
        },
        {
            type: 'Feature',
            properties: {},
            geometry: {
                type: 'Polygon',
                coordinates: [
                    [ [16.0, 40.0], [20.0, 40.0], [20.0, 50.0], [16.0, 50.0], [16.0, 40.0] ]
                ]
            }
        }
    ]
};

const greenStyle = new Style({
    stroke: new Stroke({color: 'green', width: 3}),
    fill: new Fill({color: 'rgba(0, 255, 0, 0.1)'})
});

const redStyle = new Style({
    stroke: new Stroke({color: 'red',width: 3}),
    fill: new Fill({color: 'rgba(255, 0, 0, 0.1)'})
});

const blueStyle = new Style({
    stroke: new Stroke({color: 'blue', width: 3}),
    fill: new Fill({color: 'rgba(0, 0, 255, 0.1)'})
});

const vector = new VectorLayer({
    source: new VectorSource({
        features: (new GeoJSON()).readFeatures(geojsonObject, {featureProjection: 'EPSG:3857'})
    }),
    style: greenStyle
});

const select = new Select({
    condition: function(mapBrowserEvent) {
        return click(mapBrowserEvent) && altKeyOnly(mapBrowserEvent);
    },
    style: redStyle
});

map.addInteraction(select);
select.on('select', (e) => {
    console.log('selected:', e);
});

const firstFeature = vector.getSource().getFeatures()[0];
firstFeature.setStyle(blueStyle);

setStyle overwrites style of Select interaction

  • 1
    That's correct. Feature styles override both layer and interaction styles. If you use feature styles you need to handle changes on selection and deselection yourself. A better solution may be to use a style function for the layer and set a color property on the feature which can be used by the function. – Mike Apr 24 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.