Leaflet.js 鼠标悬停时多段线颜色变化

Leaflet.js polyline color change on mouseover

我使用 Leaflet 中的点列表绘制了一条折线。这是代码

road= new L.Polyline(pointList, {
    color: color,
    weight: 10,
    lineCap:"square",
    lineJoin:"bevel",
    opacity: 0.6,
    smoothFactor: 1
    }); 

我需要在鼠标悬停时将此折线的颜色更改为绿色。我正在使用以下代码。但是没用。

road.on('mouseover', function (e) {
         var layer=e.target;
         layer.options["color"]="green";
         console.log(layer.options["color"]);

        });

任何人都可以告诉我我该怎么做吗?

你应该使用 setStyle method,像这样:

road.on('mouseover', function() {
    this.setStyle({
        color: 'red'   //or whatever style you wish to use;
    });
});

此外,要恢复到 mouseout 的初始样式,请将该样式保存在一个变量中,然后写入:

road.on('mouseout', function() {
    this.setStyle(initialStyle)
});