javascriptopenstreetmapcartographyopenlayers-6

OpenLayers change color of feature on runtime


I use OpenLayers v6.3.1, including the following stylesheet and script: Scriptfile, Stylesheet

Goal:

My goal is to change the color of a feature (LineString) on runtime using javascript.

Setup:

I mainly used the code from this website: 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
            })
        });

In this piece of code I create a line between two coordinates:

    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);

Which gives me this map: Map

I want to change the color of the line at runtime.

What I tried so far: I tried to change the color using the following code:

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

The value of the color did change, but the color of the line itself remains the same.


Solution

  • OK, i figured it out. The style can be changed with the setStyle() function which is part of the line object.

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

    This is definitely not the best solution so I am open to anything better.

    EDIT:

    As mentioned by @Mike in the comments, line.getStyle().getStroke().setColor('#123') works just fine