[GIS] Openlayers 3 – Line with two points

draw-interactiongeometryopenlayers

I'm trying to create a tool which enables the user to draw a linestring with only 2 points. It's surprising how long I've searched and can't find an example or someone asking the question.

I know that there is a potential maxPoints property but I don't know how to apply it. My guess is that it involves defining a geometry function on the linestring draw interaction but I'm struggling to make it work.

This is what I've got so far:

var vecSource = session.activeRoute.Layer.getSource();
// setup draw interaction
session.draw = new ol.interaction.Draw({
    source: vecSource,
    type: geomtype,
    geometryFunction: geometryFunction,
    maxPoints: maxPoints
});

    if (geomtype === 'Line') {
    maxPoints = 2;
    geomtype = 'LineString';
    geometryFunction = function (coords, geom) {
        geom = new ol.geom.LineString();
        coords = geom.getCoordinates();
        if (coords.length == 2) {
            finishDrawing();
        }
    }
}

I realise this probably doesn't make any sense but I've tried several different methods and this is the best I've come up with. A linestring has been created but length and geom = null when I test this.

Can anyone please offer any insight?

Best Answer

Just use the maxPoints parameter:

map.addInteraction(new ol.interaction.Draw({
  source: source,
  type: 'LineString',
  maxPoints: 2
}));

Here a JSFiddle