OpenLayers 3 select style

2019-09-09 12:26发布

问题:

In OL2 I was able to specify a "select" style in the style definition. In OL3 this doesn't seem to exist. If I understand it correctly, I can set a style for the select interaction. However, this likely won't work in my case since every layer has a unique "selected" style. Am I mistaken in my assessment of the capability? Is there another/optimal way to do this in OL3?

回答1:

Let's assume that you have a style parameter stored in each ol.Feature, you can add a ol.style.StyleFunction to your ol.interaction.Select and return a style based on this parameter. Like so:

var styles = {
  'route': new ol.style.Style({
    stroke: new ol.style.Stroke({
      width: 6,
      color: [237, 212, 0, 0.8]
    })
  }),
  'icon': new ol.style.Style({
    image: new ol.style.Icon({
      anchor: [0.5, 1],
      src: 'pin.png'
    })
  }),
  'geoMarker': new ol.style.Style({
    image: new ol.style.Circle({
      radius: 7,
      snapToPixel: false,
      fill: new ol.style.Fill({color: 'black'}),
      stroke: new ol.style.Stroke({
        color: 'white',
        width: 2
      })
    })
  })
};

var select = new ol.interaction.Select({
  style: function(feature, resolution) {
    return [styles[feature.get('style_parameter')]];
  }
});

And your feature would be like:

var geoMarker = new ol.Feature({
  style_parameter: 'geoMarker',
  geometry: new ol.geom.Point([0,0])
});