Mark
Mark

Reputation: 519

How to apply a style to the modify interaction in OpenLayers 3?

I have a GeoJSON vector layer with polygons. When the user clicks on a polygon, it should be highlighted a certain way. That works fine this way:

selectStyle = new ol.style.Style({ ... });
map = new ol.Map({ ... });
map.addLayer(vectorLayer);

var select = new ol.interaction.Select({
  condition: ol.events.condition.click,
  style: selectStyle
});
map.addInteraction(select);

Now there's an option to edit the selected polygon. I do it like this:

modify = new ol.interaction.Modify({
  features: select.getFeatures(),
  // style: modifyStyle // does not work!
});  
map.addInteraction(modify);     

Now I want to apply once more another style to the polygon that is edited, however, I couldn't figure out how. Applying the style option to the modify interaction as shown above (commented out) doesn't seem to work. Is it somehow possible?

Upvotes: 3

Views: 5134

Answers (2)

Mark
Mark

Reputation: 519

It seems like the style option in ol.interaction.Select caused my problem. If a style is set to a feature explicitly with feature.setStyle(), the style option in ol.interaction.Select won't apply anymore. I got it to work by assigning the styles explicitly.

First I set the default style to the layer:

var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: defaultStyle
});

Now I set the select styles with listeners:

var collection = select.getFeatures();
collection.on('add', addSelectionListener);
collection.on('remove', removeSelectionListener); 

function addSelectionListener(){
  var collection = select.getFeatures();
  collection.forEach(function(feature){
  feature.setStyle(selectStyle);
  });
}

function removeSelectionListener(){
  var collection = vectorLayer.getSource().getFeatures();
  collection.forEach(function(feature){
  feature.setStyle(defaultStyle);
  });
}

When modifying a feature, I assign the modify style:

modify = new ol.interaction.Modify({
  features: select.getFeatures()
});  
map.addInteraction(modify);

var collection = select.getFeatures();
collection.forEach(function(feature){
    feature.setStyle(modifyStyle);
});

Finally, after finishing the feature modification I reassign the default style:

map.removeInteraction(modify);

var collection = select.getFeatures();
collection.forEach(function(feature){
    feature.setStyle(defaultStyle);
});

select.getFeatures().clear();  

Upvotes: 2

Jonatas Walker
Jonatas Walker

Reputation: 14150

Make use of modifyend event and loop through modified features:

modify.on('modifyend', function(evt){
    var collection = evt.features;

    collection.forEach(function(feature){
        feature.setStyle(style_modify);
    });
});

Upvotes: 0

Related Questions