Don
Don

Reputation: 4202

How to style path in leaflet?

I have line geometry that I've styled using the dashArray option. I'm trying to add a black outline to distinguish the gaps on lighter basemaps.

I tried adding a black path underneath with a heavier weight to create the outline but it seems that the gaps are transparent.

Applying the following style to the respective layers creates a white line with a black outline:

path = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

When I apply dashArray the bottom layer shows through:

path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}

outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

Is there a simple way to achieve this?

Leaflet path style options here.

EDIT: Top path is dashArray by itself. Second is when I overlay the dashArray on the wider black line (outline). Third is what I'm trying to achieve.

enter image description here

Upvotes: 1

Views: 15686

Answers (2)

Don
Don

Reputation: 4202

The solution I came up with combines the two examples using three layers placing the dashArray path on top of the black-outlined layer.

//base layer black & wider to create outline
outline = {
    color: '#000000',
    weight: 5,
    opacity: 1
}

//white line layer that will show through the transparent gaps
pathBackground = {
    color: '#ffffff',
    weight: 3,
    opacity: 1
}

//dashed path is placed on top of the black-outlined white line
path = {
    color: '#000000',
    weight: 3,
    opacity: 1,
    dashArray: '5,10'
}

Upvotes: 0

ghybs
ghybs

Reputation: 53205

You could achieve the same effect with just 2 paths:

  1. Background, continuous and wider.
  2. Foreground, dashed and narrower. The background is visible through the gaps.

It is not exactly the same result, since if you want round caps, it is the white dashes that get them. But if you want actually square caps, as shown below, then you get the same effect:

dashed path

var map = L.map("map").setView([0.4, 0], 8);
var coords = [
  [0, -1],
  [0, 1],
  [1, 1]
];

// Background continuous black stroke, wider than dashed line.
L.polyline(coords, {
  weight: 10,
  lineCap: 'square', // Optional, just to avoid round borders.
  color: 'black'
}).addTo(map);

// Foreground dashed white stroke, narrower than background.
L.polyline(coords, {
  weight: 6,
  dashArray: '5, 10',
  lineCap: 'square', // Optional, just to avoid round borders.
  color: 'white'
}).addTo(map);
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet-src.js"></script>
<div id="map" style="height: 200px"></div>

Upvotes: 5

Related Questions