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) {

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?

1 Answer 1


Just use the maxPoints parameter:

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

Here a JSFiddle

  • Thanks Lars, I was obviously making this far more complicated than I needed to!
    – dvmac01
    Commented Aug 1, 2016 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.