TransWikia.com

Changing style of a LineString in OpenLayers 6

Geographic Information Systems Asked on June 20, 2021

I am using OpenLayers 6.5 and I have a linestring added as a map layer. I am having trouble accessing the feature (linestring) in order to change the style .

Here is how I create it

var lineString = new ol.layer.Vector({
    id: 'MarkersTrail' + myid,
    source: new ol.source.Vector({
        features: [
            new ol.Feature({
                id: myid,
                geometry: new ol.geom.LineString(points),
                name: myid
            })
       ]
   }),
   style: new ol.style.Style({                    
       stroke : new ol.style.Stroke({ 
           color: '#0000ff',
           width: 5
       })
   })


  });
   map.addLayer(lineString);
   lineString.setVisible(false);

When I then try to access it my feature is null?

layer is determined by map.getLayers().

var feature = layer.getSource().getFeatureById(myid);

What am I doing wrong?

One Answer

Assigning an id to a feature in OpenLayers is not done through id option, but with the setId method.

Your code could then look something like this:

var myFeature = new ol.Feature({
  geometry: new ol.geom.LineString(points),
  name: myid
});
myFeature.setId(myid);

var lineString = new ol.layer.Vector({
  id: 'MarkersTrail' + myid,
  source: new ol.source.Vector({
    features: [myFeature]
  }),
  style: new ol.style.Style({                    
     stroke : new ol.style.Stroke({ 
         color: '#0000ff',
         width: 5
     })
});

Answered by TomazicM on June 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP