I have one function which creates poly line & adds that polyline to map

function makeRoute(e)
    if(pointsSelection.length > 0)
        var firstpolyline = new L.Polyline(pointsSelection, {
        color: 'blue',
        weight: 5,
        smoothFactor: 1



        selection = [];
        pointsSelection = [];
        alert("Please select more than one point");

my problem is that It adds line with same color every time.

I want to add poly lines with different colors every time.

So how can I change color of polyline dynamically.

  • 1
    You could use something like this function in place of 'blue'. If you want something a little less random, I suggest you define a color palette as an array and select sequentially from that. stackoverflow.com/questions/1484506/… Mar 12, 2013 at 10:49

1 Answer 1


You can use this for creating dynamic colors

var color;
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
color= "rgb("+r+" ,"+g+","+ b+")"; 

then use this

var firstpolyline = new L.Polyline(pointsSelection, {
    color: color,
    weight: 5,
    smoothFactor: 1

I think this answer will helps you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.