0

Using openlayer 3.3.0, we have a map divided into counties, each county is a 'feature', I want to select a feature and change its border colour, when I select another feature, I want the previously selected feature to revert back to its original style and the new feature to have the selected style applied.

So I use this to add the interactions.

var select = new ol.interaction.Select({ 
            condition: ol.events.condition.click,
        });
select.on('select', function(evt){
    var features = evt.target.getFeatures();
    features.forEach(function(feature){
        feature.setStyle(new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: '#007aa9',
                    width: 1.5;
                }))
    }
})
map.addInteraction(select);

This all works fine, but it doesn't 'unselect' the previously selected feature, so if I click around all the features get the select style

The only way I can seem to fix this is, to set a 'previouslySelectedFeature' variable, and reset its style in the 'on' event, it seems a bit clunky though, shouldn't there be a way to detect when a feature has been 'unselected' and reset its style?

BrokenEyes
  • 192
  • 2
  • 18

1 Answers1

0

Would appear the solution might be to update to version 3.4 (it doesn't work in 3.3) and then you get access to 'selected' and 'deselected' properties. So I refactored my event code to

            select.on('select', function(evt){
                var selectedFeatures = evt.selected;
                selectedFeatures.forEach(function(feature){
                    feature.setStyle(new ol.style.Style({
                        stroke: new ol.style.Stroke({
                        color: '#007aa9',
                        width: 1.5;
                       }));
                });
                var deselectedFeatures = evt.deselected;
                deselectedFeatures.forEach(function(feature){
                    feature.setStyle(new ol.style.Style({
                        stroke: new ol.style.Stroke({
                        color: '#000000',
                        width: 0.4;
                       })
                    })
                });
            });

Right or wrong?

BrokenEyes
  • 192
  • 2
  • 18