简体   繁体   中英

Openlayers3 - How to anchor a text label to a point?

I am working on an application using Openlayers3. On the map there are a couple of line segments and text labels. Each line has a color and an associated label.

For the map, I would like to have the text label anchored at a point of a line segment that is drawn on the map. So if I move the map or zoom in or out, that the label sticks to the point. However, if I zoom in or out the labels move (a lot). Dragging the map does not have this effect. Somehow I would like them to stick at a point on the line rather than move around.

Does anyone has some clever advice or links where to look? Googling for terms like 'anchor' or 'fixed point' and trying some of the recommendations did not solve the issue for me. Any help would be very much appreciated!

maybe you can be inspered by the "arrow" example wich use a style function that use geometry segments:

http://jsfiddle.net/davidhequet/7asg74Lc/

var styleFunction = function(feature, resolution) {
  var geometry = feature.getGeometry();
  var styles = [
    // linestring
    new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#ffcc33',
        width: 2
      })
    })
  ];

  geometry.forEachSegment(function(start, end) {
    var dx = end[0] - start[0];
    var dy = end[1] - start[1];
    var rotation = Math.atan2(dy, dx);
    // arrows
    styles.push(new ol.style.Style({
      geometry: new ol.geom.Point(end),
      text: new ol.style.Text({
            textAlign: 'left',
            textBaseline: 'bottom',
            font: 'Arial',
            text: 'test text',
            fill: new ol.style.Fill({color: 'red'}),
            stroke: new ol.style.Stroke({color: 'white', width: '2'}),
            offsetX: 0,
            offsetY: 0,
            rotation: 0
          })
    }));
  });

  return styles;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM