在传单中创建不同颜色的折线

create polylines with different colors in leaflet

本文关键字:颜色 折线 单中 创建      更新时间:2023-09-26

我有一个函数创建多晶线&将折线添加到映射

        function makeRoute(e)
    {
        if(pointsSelection.length > 0)
        {
            pointsSelection.push(e.target.getLatLng());
            var firstpolyline = new L.Polyline(pointsSelection, {
            color: 'blue',
            weight: 5,
            smoothFactor: 1
            });
            firstpolyline.addTo(map);
            pointsArrayCollection.push(pointsSelection);
            polyArrayCollection.push(firstpolyline);
            selection = [];
            pointsSelection = [];
        }
        else
        {
            alert("Please select more than one point");
        }
    }

我的问题是它每次都添加相同颜色的线。

我想每次都添加不同颜色的多聚线。

如何动态改变折线的颜色

对于改变颜色,我使用随机颜色生成器函数。

使用get_random_color()代替'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;
}

扩展viabhav shah的答案(这是正确的),你的总解决方案将是:

function makeRoute(e) {
    if(pointsSelection.length > 0) {
        pointsSelection.push(e.target.getLatLng());
        var firstpolyline = new L.Polyline(pointsSelection, {
        color: get_random_color(),
        weight: 5,
        smoothFactor: 1
        });
        firstpolyline.addTo(map);
        pointsArrayCollection.push(pointsSelection);
        polyArrayCollection.push(firstpolyline);
        selection = [];
        pointsSelection = [];
    } else {
        alert("Please select more than one point");
    }
    // Function to create a random color
    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;
    }
}

Vaibhav Shah有正确答案,所以请为他的解决方案投票。