Cary
Cary

Reputation: 51

Mapbox js: Changing the different latlng of a polyline based on properties

I have an array of objects, each contains the coordinates and different properties. Now I want to draw a polyline of those latlng objects on my map that changes the color based on the property of the object. But since I could find out the polyline only has one color object.. So I can not define different colors for different points on the polyline.. Is that somehow possible? I couldn't find anything like that for the googlemaps or here API either..

Thanks a lot!

Upvotes: 1

Views: 2447

Answers (1)

leopectus
leopectus

Reputation: 862

You are correct that when using the HERE API, a Polyline can only have one color. A workaround might be to draw several lines, each with its own color. Let's give this a try.

The following example takes an array with lat/long and color information and uses this to draw a series of lines. By adding all the lines to a Group, we're able to handle them like a single object.

var matrix = [
  [new H.geo.Point(41.759876, 12.942710), 'red'],
  [new H.geo.Point(41.768711, 12.947602), 'orange'],
  [new H.geo.Point(41.772936, 12.956271), 'yellow'],
  [new H.geo.Point(41.773704, 12.964082), 'green'],
  [new H.geo.Point(41.770824, 12.975497), 'blue'],
  [new H.geo.Point(41.764230, 12.980647), 'indigo'],
  [new H.geo.Point(41.758596, 12.982965), 'violet']
];

var rainbowGroup = new H.map.Group();

function drawRainbow(map) {
  map.addObject(rainbowGroup);
  for (var i = 0, len = matrix.length-1; i < len; i++) {
    addRainbowSegment(matrix[i], matrix[i+1], map);
  }
}

function addRainbowSegment(point, nextPoint, map) {
  var strip = new H.geo.Strip();
  strip.pushPoint(point[0]);
  strip.pushPoint(nextPoint[0]);
  rainbowGroup.addObject(new H.map.Polyline(
    strip, { style: { lineWidth: 20, strokeColor: point[1] }}
  ));
}

The end result should look like a continuous line, where each segment has a different color. Something like this:

enter image description here

Look! A rainbow! (Unicorns sold separately.)

Upvotes: 1

Related Questions