2

I am new to OpenLayers.

Is it possible to assign color not to the whole linestring, but to different segments?

0

3 Answers 3

2

With newer OpenLayers versions it's quite possible to color each segment of the line string with it's own color. Style function has to be created where line string geometry is iterated through segments and separate style with it's own geometry and color is created for each segment.

Styles created for segments has to be saved as property of the line feature so they are not recreated each time map is redrawn.

Function for coloring line sections with random colors could then look something like this:

function style(feature, resolution) {
  var style = feature.get('segmentStyles');
  if (!style) {
    style = [];
    const geometry = feature.getGeometry();
    geometry.forEachSegment(function (start, end) {
      style.push(new ol.style.Style({
        geometry: new ol.geom.LineString([start, end]),
        stroke: new ol.style.Stroke({
          color: '#'+(0x1000000+Math.random()*0xffffff).toString(16).substr(1,6),
          width: 3
        })
      }));
    });
    feature.set('segmentStyles', style);
  }
  return(style);
}

Here is an example of using this style:

enter image description here

1

It is not possible using OpenLayers 2.x.

At those versions you will have to break up your lines and assign different styles to each of them.

-2

All GIS tools treat a set of connected nodes not having same start and end nodes as a single linestring unless you break it explicitly as mentioned by @unicoletti. OpenLayers is not an exception to that. You can do it using code to break up every node and visualize on web or whatever.

However, this creates a problem that GIS tools will not consider it as a single valid linestring. The only answer is to hack into OpenLayers code and consider each line as a set of two nodes which are drawn individually. or create a different layer with your line broken into a set of two nodes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.