'How to get a fixed number of coordinates between two points polyline in Javascript

I'm looking for a way to find multiple coordinates between 2 points in Javascript (I don't need distance or mid point).

Say I have these 2 points:

  • Point A (left) lat: 39.091868 long: -9.263187
  • Point B (right) lat: 39.089815 long: -9.261857

2 points polyline

I want to generate for instance 20 coordinates between points A and B.

I tried using this piece of Javacript code (Found on an old thread):

   Point = function(x, y) {
      this.x = x;
      this.y = y;
    }
    var pointA = new Point(39.091868, -9.263187);
    var pointB = new Point(39.089815, -9.261857);
    
    var numberOfPoints = 20;
    var points = new Array();
    
    for (var i = 0; i < numberOfPoints; i++) {
      points.push(new Point((Math.abs(pointA.x - pointB.x) / 10) * i + pointB.y, (Math.abs(pointA.y - pointB.y) / numberOfPoints) * i + pointB.y));
    }
    
    console.log(points);

When I run the code above, it prints out 20 values of the points array between point A and B. However, it only seems to store the correct longitude values of the points. (x and y both show longitude values). For example, the first item of the points array is:

Point x: -9.261857 y: -9.261857

How should I adjust the calculation inside the for loop so that each point between point A and B also stores a correct latitude value? Or does anyone know another way to calculate a fixed number of coordinates between 2 points in Javascript?

Any kind of help is appreciated



Solution 1:[1]

Because the earth is not flat, the calculation can be good for small distance.

Just calculate the point. 1 Degree is approximal 110 km. so you may do just Pitagoras calculation for small distance and multiply by 110 km, and do iterative loop.

For accuracy you may use open-layers library (most of it is free), but you should provide map with projection. Make things a bit complicated.

One of the function is find the coordinate of a specific point, give distance and azimuth.

Need to find the the azimuth first of two points.

Use O/L: openlayers sphere getlength & bearing.

O/L distance

Open layers

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eitan