Search code examples
javascriptopenlayersopenlayers-6

Extending LineString/MultiLineString along existing Feature


I have given coordinates of two points. I can draw a LineString that is connecting these two points. What I'd like to achieve is having a LineString/MultiLineString that's connecting points but it's also a little longer (let's say 20% longer than distance between these two points) and it's extended after one point only.

What I currently have: enter image description here

What I want to achieve: enter image description here

My issue is that I don't know how to find position of third point which would indicate end of the line. It should be placed exactly along existing line in given distance. Any kind of map projection is not important, because I just want to have a line that will be always straight.

const markerOne = new ol.Feature({
  geometry: new ol.geom.Point([-1000, -1000])
});

const markerTwo = new ol.Feature({
  geometry: new ol.geom.Point([1000, 1000])
});

const lineStrEnd = ?;

const lineStr = new ol.Feature({
 geometry: new ol.geom.LineString([markerOne.getGeometry().getCoordinates(), lineStrEnd])
});

HERE'S WORKING FIDDLE


Solution

  • The simplest way would be to scale the geometry, e.g. a linestring from markerOne to markerTwo increased by 20% with the scaling anchored at markerOne so the line extents beyond markerTwo

    const lineStr = new ol.Feature({
     geometry: new ol.geom.LineString([markerOne.getGeometry().getCoordinates(), markerTwo.getGeometry().getCoordinates()])
    });
    
    lineStr.getGeometry().scale(1.2, 1.2, markerOne.getGeometry().getCoordinates());