javascript - 如何将样式应用于 OpenLayers 3 中的修改交互?

标签 javascript openlayers-3

我有一个带有多边形的 GeoJSON 矢量图层。当用户点击一个多边形时,它应该以某种方式突出显示。这样效果很好:

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);

现在有一个选项可以编辑选定的多边形。我这样做:

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

现在我想再次对已编辑的多边形应用另一种样式,但是,我不知道该怎么做。如上所示(已注释掉)将样式选项应用于修改交互似乎不起作用。这有可能吗?

最佳答案

似乎 ol.interaction.Select 中的样式选项导致了我的问题。如果使用 feature.setStyle() 将样式显式设置为功能,则 ol.interaction.Select 中的样式选项将不再适用。我通过显式分配样式让它工作。

首先我为图层设置默认样式:

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

现在我用监听器设置选择样式:

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);
  });
}

修改功能时,我指定修改样式:

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

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

最后,在完成功能修改后,我重新分配了默认样式:

map.removeInteraction(modify);

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

select.getFeatures().clear();  

关于javascript - 如何将样式应用于 OpenLayers 3 中的修改交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32524122/

相关文章:

javascript - Asp.NET 内联脚本中的空格

javascript - 将事件监听器附加到整个 html 文档的最佳方式

javascript - 断言错误: Assertion failed: length of coordinate array should match stride

jquery - Openlayers3 : Abort the Draw Interaction

javascript - 如何在 Openlayers 3 ol.interaction.Select 上手动引发 'select' 事件?

javascript - 使用 JavaScript 启用 CSS 幻灯片自动播放

javascript - 将事件连接到某个标签或某个类的所有 html 元素

javascript - OpenLayers 3.13 : issue with bindTo by linking two views

javascript - 无法让我的 openlayers map 出现在网页上

javascript - 无法根据 bootstrap 3 中的下拉选择在输入字段中获取值