Drawing a Speed Leader line in OpenLayers
Asked Answered
J

1

3

I'm trying to draw an icon representing a entity on an OpenLayers map that includes a "speed leader", which is a small line segment that originates at the icon and draws outward in the direction the entity is moving. The length of the line indicates the speed of entity.

The problem I'm running into is that I want the length of the line to be relative to screen coordinates, but the angle and position of the line to be relative to map coordinates. Thus, when zooming in, I would not expect the line to become longer, but when panning or rotating, it should translate/rotate.

I'm tempted to use getPixelFromCoordinate / getCoordinateFromPixel to figure out what map coordinate corresponds to my line end points, then add some hook to recalculate the line segment every time the user zooms the map. Is there a better way?

Edit: I'm using OpenLayers 3. However, if anyone has a solution for an older version, I'd like to hear it. It may be similarly named in the new version.

Jointless answered 1/5, 2015 at 19:1 Comment(1)
I ended up using a LineString Geometry and some trigonometry to do this, worked quite well.Linin
W
5

In this case it would make sense to use a ol.style.StyleFunction(feature, resolution) which returns an array of two styles. The first style is for the point, the second style for the "speed leader". The style for the "speed leader" uses a custom geometry which is calculated with the view resolution to always use the same length in pixels.

var style = function(feature, resolution) {
  var length = feature.get('speed'); // in pixel
  var pointFrom = feature.getGeometry().getCoordinates();
  var pointTo = [
      pointFrom[0] + length * resolution,
      pointFrom[1] + length * resolution
  ];
  var line = new ol.geom.LineString([
      pointTo,
      pointFrom
  ]);

  return [
    // the style for the point
    new ol.style.Style({ ... }),
    // the style for the "speed leader"
    new ol.style.Style({
      geometry: line,
      stroke: new ol.style.Stroke({ ... })
    }),
  ];
};

http://jsfiddle.net/annyL2sc/

In this example I am not taking the direction into account, but I think it shows the idea.

Workhouse answered 2/5, 2015 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.