OpenLayers Symbology – Creating Black and White Dotted Line on Map

openlayerssymbology

Currently I am getting only a white dotted line in my map using the code below:

style: new ol.style.Style({
                                    stroke: new ol.style.Stroke({
                                      color:[255, 255, 255, 1.0],
                                      opacity: 1,
                                      width: 4,
                                      lineDash: [4, 4]
                                      }),
                                      fill: new ol.style.Stroke ({
                                          color: [155, 155, 155, 0.4]
                                      })

                      })

But my requirement is to get black and white dotted lines in the form black white black white…

Best Answer

You can set more than one style for a layer and overlay them

Go to http://openlayers.org/en/v4.6.5/examples/vector-layer.html, open the console and execute the following

// Array of styles with continuous black line below (first style)
var newstyle = [
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color:[0, 0, 0, 1.0],
      opacity: 1,
      width: 4
    })
    // Commented to only see the lines
    //,fill: new ol.style.Stroke ({
    //  color: [155, 155, 155, 0.4]
    //})
  }),
  // Dash white lines (second style, on the top)
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color:[255, 255, 255, 1.0],
      opacity: 1,
      width: 4,
      lineDash: [10, 20, 10, 20]
    })
  })
];

vectorLayer.setStyle(newstyle);

To grasp dash pattern (for white lines), you can go to http://phrogz.net/tmp/canvas_dashed_line.html (link borrowed from answer Dashed lines in OL3?)

PS: contrary to @JGH other answer, I didn't bother with offset and instead choose to add dash lines on top of a continuous line. Both approaches are valid, just a question of preferences.

Related Question