How do I make a two-color dashed line style in OpenLayers?
Asked Answered
P

2

9

I want to add a dashed stroke with two alternating colors to a feature in OpenLayers. Basically, I want to create a two color outline around polygon so that it shows up no matter what color the background is. I want the end result to look like this;

OpenLayers two color stroke example

How can I define that kind of style in OpenLayers?

Perspiration answered 17/8, 2017 at 16:29 Comment(0)
P
15

The style property of a Vector layer accepts an array of values in addition to a single value, so you can create two dashed strokes using lineDash and give them different lineDashOffset values;

var lightStroke = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: [255, 255, 255, 0.6],
    width: 2,
    lineDash: [4,8],
    lineDashOffset: 6
  })
});

var darkStroke = new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: [0, 0, 0, 0.6],
    width: 2,
    lineDash: [4,8]
  })
});

Then apply them to the same layer like this;

var myVectorLayer = new ol.layer.Vector({
  source: myPolygon,
  style: [lightStroke, darkStroke]
});
Perspiration answered 17/8, 2017 at 16:29 Comment(0)
T
1

Style in Vector Layer can fill by array of styles or function.

  1. defines your styles
public styles = {
  'Point': new Style({
    image: this.image
  }),
  'LineString': new Style({
    stroke: new Stroke({
      color: 'green',
      lineDash: [4],
      width: 2
    })
  }),
  'Polygon': new Style({
    stroke: new Stroke({
      color: 'blue',
      lineDash: [4],
      width: 3
    }),
    fill: new Fill({
      color: 'rgba(255, 0, 255, 0.1)'
    })
  }),
  'Circle': new Style({
    stroke: new Stroke({
      color: 'red',
      width: 2
    }),
    fill: new Fill({
      color: 'rgba(255,0,0,0.2)'
    })
  })
};
  1. Use each of styles above in Vector Layer by function
var vector = new VectorLayer({
  source: new VectorSource({}),
  style: (feature, resolution) => {
    switch (feature.getGeometry().getType()){
      case 'Polygon':
        return this.styles['Polygon'];       
      case 'LineString':
        return this.styles['LineString'];       
    }
  }
});
Truant answered 9/7, 2020 at 11:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.