0

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.

Allerion
  • 103
  • 2
  • 4
  • 2
    The world isn’t flat so for large distances you’ll need to look at great circles rather than lines. However for small distances, subtract the lat and long of point2 from point1, and divide the differences by 1 + the number of new points you want. Starting at point1, add the divided differences to point1 lat and long, keep doing that til you have the number of new points you want. It doesn’t matter which point you start with. – James Nov 11 '22 at 19:40
  • 1
    There is a method in the `geometry` library to do this: [interpolate](https://developers.google.com/maps/documentation/javascript/reference/geometry#spherical.interpolate). [proof of concept fiddle](https://jsfiddle.net/geocodezip/62q7bohu/1/) – geocodezip Nov 13 '22 at 16:10

1 Answers1

0

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

dangarfield
  • 2,210
  • 1
  • 13
  • 18