Markus
Markus

Reputation: 2222

How to draw single line with OpenLayers3?

In this example, you can draw a path using the LineString type: http://openlayers.org/en/v3.0.0/examples/draw-and-modify-features.html

I want to do the same but with only a single line between 2 points. The draw tool should automatically finish drawing after setting the second point.

How can this be achieved?

Upvotes: 0

Views: 1828

Answers (2)

bakhansen
bakhansen

Reputation: 41

You can also set maxPoints: 2 in ol.interaction.Draw

http://openlayers.org/en/latest/apidoc/ol.interaction.Draw.html

(I guess it has been added since the original answer)

Upvotes: 1

erilem
erilem

Reputation: 2664

I just merged into the master branch a commit that addresses your use-case. See https://github.com/openlayers/ol3/pull/2927.

With this commit you can programmatically finish the drawing. The following code snippet shows how to terminate a line when it has two vertices:

var listenerKey;
drawInteraction.on('drawstart', function(e) {
  var feature = e.feature;
  var lineString = feature.getGeometry();
  // finish the drawing when the linestring has 2 vertices
  listenerKey = lineString.on('change', function(e) {
    var lineString = e.target;
    var vertices = lineString.getCoordinates();
    if (vertices.length == 3) {
      drawInteraction.finishDrawing();
    }
  });
});
drawInteraction.on('drawend', function(e) {
  ol.Observable.unByKey(listenerKey);
});

Upvotes: 2

Related Questions