OpenLayers在运行时更改功能的颜色

问题描述 投票:0回答:1

我使用OpenLayers v6.3.1,包括以下样式表和脚本:ScriptfileStylesheet

目标:

我的目标是在运行时使用JavaScript更改功能部件(LineString)的颜色。

设置:

我主要使用此网站上的代码:OpenLayers

var map = new ol.Map({
            target: 'map', //<div id="map"></div>
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            view: new ol.View({
                projection: 'EPSG:4326',
                center: [11.592581, 47.241524],
                zoom: 15
            })
        });

在这段代码中,我在两个坐标之间创建了一条线:

    var lonlat1 = [11.592581, 47.241524];
    var lonlat2 = [11.58554, 47.248958];
    //create the line's style
    var lineStyle = [
        // linestring
        new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#000',
                width: 2
            })
        })
    ];

    //create the line       
    var line = new ol.layer.Vector({
        source: new ol.source.Vector({
            features: [
                new ol.Feature({
                    geometry: new ol.geom.LineString([lonlat1, lonlat2])
                })
            ]
        }),
        style: lineStyle
    });
    map.addLayer(line);

哪个给我这张地图:Map

我想在运行时更改线条的颜色。

我到目前为止尝试过的:我尝试使用以下代码更改颜色:

line.style_[0].stroke_.color_ = '#123';

颜色的值确实发生了变化,但是线条本身的颜色保持不变。

javascript openstreetmap cartography openlayers-6
1个回答
0
投票

好的,我知道了。可以使用setStyle()函数更改样式,该函数是行对象的一部分。

line.setStyle([
    new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: '#123',
            width: 2
         })
     })
 ]);

这绝对不是最好的解决方案,所以我愿意接受更好的选择。

© www.soinside.com 2019 - 2024. All rights reserved.