Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 696
Jo Sprague Avatar asked Aug 17 '17 16:08

Jo Sprague


2 Answers

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]
});
like image 167
Jo Sprague Avatar answered Dec 31 '22 20:12

Jo Sprague


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'];       
    }
  }
});
like image 24
Omid Rahimi Avatar answered Dec 31 '22 18:12

Omid Rahimi