Search code examples
javascriptgoogle-maps-api-3polyline

Programmatically calculating and adding x points between two points on a polyline


I'm trying to programmatically calculate and add x number of equidistant points between two points on a polyline in the google maps api. For example with a polyline of two points I would like to add 5 equidistant points between them to make a total of 7. I'd like to achieve this programmatically, not via user interaction.

let path = [
    {lat : 35.20806877349178, lng : 38.14744584290822},
    {lat : 35.202442417421985, lng : 38.185044716791985},
];

path = someFunction(path);

console.log(path);
// outputs
[
    {lat : 35.20806877349178, lng : 38.14744584290822},
    // 5 new points in here
    {lat : 35.202442417421985, lng : 38.185044716791985},
];

I think that I need to start by determining direction from point A to point B, and could then get the difference between lat/lng values divide by the number of points to add and then increment/decrement lat/lng values of point A by the divided difference...I think.

I'm struggling to know where to begin with this. Any help appreciated.


Solution

  • Here's a rudimentary approach using euclidian distance (eg, imagine that there is no curvature of the earth), which should work for relatively small distances.

    const path = [{
        lat: 35.1,
        lng: 35.1
      },
      {
        lat: 36.3,
        lng: 35.7
      },
    ]
    const totalPoints = 7
    
    const equidistantPoints = (min, max, no, keys) => {
      const points = new Array(no).fill(0).map(() => ({}))
      for (const key of keys) {
        const step = (max[key] - min[key]) / (no - 1)
        for (let i = 0; i < no; i++) {
          points[i][key] = min[key] + (step * i)
        }
      }
      return points
    }
    const pathUpdated = equidistantPoints(path[0], path[1], totalPoints, ['lat', 'lng'])
    
    console.log(pathUpdated)

    If you find that you need to deal with curvature, then you need to define what is straight by which projection. In that case you should probably look at this answer: https://gis.stackexchange.com/questions/79633/how-to-determine-vector-between-two-lat-lon-points