【问题标题】:OpenLayers modify feature style without overwritting interactions styleOpenLayers 修改特征样式而不覆盖交互样式
【发布时间】:2019-04-03 00:20:48
【问题描述】:

有没有办法在不修改选择交互的默认样式的情况下修改单个功能的样式?

这是一段简单的代码,显示我的问题和jsfiddle

最小的html:

<input type="button" id="switcher" value="Change style"></input>
<div id="map" class="map"></div>

还有一个简单的脚本:

let vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({wrapX: false})
});

let map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM({wrapX: false})
    }),
    vectorLayer,
  ],
  view: new ol.View({
    center: ol.proj.transform([9, 44.65], 'EPSG:4326', 'EPSG:3857'),
    zoom: 8
  })
});

let source = vectorLayer.getSource();

let draw = new ol.interaction.Draw({
  source: source,
  type: 'Polygon'
});

let selectOnHover = new ol.interaction.Select({
    source: source,
    condition: ol.events.condition.pointerMove
});

map.addInteraction(draw);
map.addInteraction(selectOnHover);

let fill = new ol.style.Fill({
  color: 'rgba(255,0,255,0.4)'
});
let stroke = new ol.style.Stroke({
  color: '#00FF00',
  width: 5
});
let customStyle = new ol.style.Style({
  image: new ol.style.Circle({
    fill: fill,
    stroke: stroke,
    radius: 5
  }),
  fill: fill,
  stroke: stroke
});

document.getElementById('switcher').onclick = function(event) {
  let features = source.getFeatures();
  if(features.length>0)
    features[0].setStyle(customStyle);
}

正如您在 jsfiddle 上的测试所看到的,单击按钮将正确更改第一个绘制特征的样式,但似乎也覆盖了悬停时的默认样式(这里只是一个与条件的选择交互)。

如何在更改特征样式时保持默认样式?

【问题讨论】:

    标签: javascript openlayers-5


    【解决方案1】:

    功能上的样式会覆盖所有样式函数(以及交互的默认样式等)。但是你可以给一个特性一个 customStyle 属性,并且只在图层样式函数中使用它而不是默认样式,而交互将继续使用默认值进行交互。

    let defaultFill = new ol.style.Fill({
      color: 'rgba(255,255,255,0.4)'
    });
    var defaultStroke = new ol.style.Stroke({
      color: '#3399CC',
      width: 1.25
    });
    var defaultStyles = [
      new ol.style.Style({
        image: new ol.style.Circle({
          fill: defaultFill,
          stroke: defaultStroke,
          radius: 5
        }),
        fill: defaultFill,
        stroke: defaultStroke
      })
    ];
    
    let vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({wrapX: false}),
      style: function(feature) { 
        var customStyle = feature.get('customStyle');
        return customStyle || defaultStyles;
      }
    });
    
    
    ...
    ...
    
    document.getElementById('switcher').onclick = function(event) {
      let features = source.getFeatures();
      if(features.length>0)
        features[0].set('customStyle', customStyle);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      相关资源
      最近更新 更多