Leaflet Colours for Polylines

Change polyline options leaflet

L.Polyline is extended from L.Path which has a setStyle method:

polyline.setStyle({
color: 'black'
});

Example: http://plnkr.co/edit/kfLcoG?p=preview

Reference: http://leafletjs.com/reference.html#path

Leaflet multi-color polyline

There a few libraries like https://github.com/Oliv/leaflet-polycolor
But you don't need a library for this.

You have your "main" polyline and from this you generate new lines segments.

   var poly = L.polyline([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047],
[51.51, -0.06],
]);
//.addTo(map); Don't add the main line to the map

setPolylineColors(poly,['#f00','#ff0','#000'])

function setPolylineColors(line,colors){

var latlngs = line.getLatLngs();

latlngs.forEach(function(latlng, idx){
if(idx+1 < latlngs.length ){
var poly = L.polyline([latlng,latlngs[idx+1]],{color: colors[idx]}).addTo(map);
}
})
}

Example: https://jsfiddle.net/falkedesign/2b8t3v6f/

How to assign different colors to polyline segments in Leaflet R

You mentioned performance was an issue, for which I recommend using mapdeck to do the plotting

In this example I'm plotting 100,000 lines, coloured by a group variable.

Setting up the data

For the data I'm putting the origin & destination coordinates in the same row. And using data.table to make it.

library(data.table)

lons <- seq(-180, 180, by = 0.0001)
lats <- seq(-90, 90,by = 0.0001)
n <- 1e5
dt <- data.table(
lon = sample(lons, size = n)
, lat = sample(lats, size = n)
, group = sample(c(1,2), replace = T, size = n)
)

dt[
, `:=`(
lon_to = shift(lon, type = "lead")
, lat_to = shift(lat, type = "lead")
)
]

Plot

You need a Mapbox API key for the underlying base map

Use the add_line() function to create a coloured line between a given origin & destination

mapdeck() %>%
add_line(
data = dt
, origin = c("lon","lat")
, destination = c("lon_to", "lat_to")
, stroke_colour = "group"
)

Sample Image

It's a mess because I've just sampled random points, but you get the idea.

create polylines with different colors in leaflet

For changing color I am using random color generator function.

Use get_random_color() in place of 'blue':

function get_random_color() 
{
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ )
{
color += letters[Math.round(Math.random() * 15)];
}
return color;
}

changing the color of polylines and marker icon's when the layer changes?

I am not sure if I understood correctly but here is what you can do.

If you want to toggle between markers with polylines and assign different color you can use this plugin and return icon markers by passing the color.

 const icon = (color) => L.icon({
iconSize: [25, 41],
iconAnchor: [10, 41],
popupAnchor: [2, -40],
iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${color}.png`,
shadowUrl: "https://unpkg.com/leaflet@1.6/dist/images/marker-shadow.png"
});

and then you have the latlngs and assing to the markers an icon with the prefered color

var places1 = [
{ latlng: [39.61, -105.02], popup: 'This is Littleton, CO.'},
{ latlng: [39.74, -104.99], popup: 'This is Denver, CO.'},
{latlng: [39.73, -104.8], popup: 'This is Aurora, CO.'}
];

places1.forEach(place => L.marker(place.latlng, {
icon: icon('violet')
}).bindPopup(place.popup).addTo(cities1))

and here define the polyline color

L.polyline(places1.map(({latlng}) => latlng), {
color: 'purple'
}).addTo(cities1);

Similarly you can follow the same steps for any other overlay

<!DOCTYPE html>
<html>

<head>

<title>Layers Control Tutorial - Leaflet</title>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>

<style>
html,
body {
height: 100%;
margin: 0;
}

#map {
width: 600px;
height: 400px;
}
</style>

</head>

<body>

<div id='map'></div>

<script>
var cities1 = L.layerGroup();
var cities2 = L.layerGroup();

var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
});

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

const icon = (color) => L.icon({
iconSize: [25, 41],
iconAnchor: [10, 41],
popupAnchor: [2, -40],
iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${color}.png`,
shadowUrl: "https://unpkg.com/leaflet@1.6/dist/images/marker-shadow.png"
});

var places1 = [{
latlng: [39.61, -105.02],
popup: 'This is Littleton, CO.'
},
{
latlng: [39.74, -104.99],
popup: 'This is Denver, CO.'
},
{
latlng: [39.73, -104.8],
popup: 'This is Aurora, CO.'
}
];

places1.forEach(place => L.marker(place.latlng, {
icon: icon('violet')
}).bindPopup(place.popup).addTo(cities1))

var places2 = [{
latlng: [39.77, -105.23],
popup: 'This is Golden, CO.'
},
{
latlng: [39.75, -105.16],
popup: 'This is Applewood, CO.'
}
];

places2.forEach(place => L.marker(place.latlng, {
icon: icon('orange')
}).bindPopup(place.popup).addTo(cities2))

L.polyline(places1.map(({
latlng
}) => latlng), {
color: 'purple'
}).addTo(cities1);

L.polyline(places2.map(({
latlng
}) => latlng), {
color: 'orange'
}).addTo(cities2);

var overlays = {
"cities1": cities1.addTo(map),
"cities2": cities2
};

L.control.layers(null, overlays).addTo(map);
</script>

</body>

</html>


Related Topics



Leave a reply



Submit