Drawing a Speed Leader line in OpenLayers

南笙酒味 提交于 2019-12-31 01:39:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/29993323/drawing-a-speed-leader-line-in-openlayers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!