# Moving a point along google map Polyline

My goal to simulate the motion of a car on a given road. To do that, I use google map direction API to fetch the direction polyline (an array of LatLng)

Now every second, I calculate the new position of the car based on its speed and its previous position.

And the cycle repeats every second.

To simplify my problem, let's say that the car is moving along a straight road with a certain velocity.

The google direction API will give me an array of only two LatLng, A and B (The start point and finish point since the road is straight)

Based on the velocity of the car and delta time, I calculated the car has moved away from point A towards B by a distance D in meters.

If I know the coordinates of A, B and the value of D, how do I calculate the new position of the car?

MY ATTEMPT

My attempt assumes that the Earth is Flat and the LatLng A and B are cartesian coordinates in 2D planes. So I just used the cartesian rule taken from here Finding a point along a line a certain distance away from another point!

/**
* A to B is a straight line on the Map
* A is the origin
* B is the destination
* d is the distance offset from A
**/
function getNewPosition(A, B, d){
const t = d / distanceBetweenTwoLatLng(A, B)
const lat = (1-t)*A.lat+t*A.lng
const lng = (1-t)*B.lng+t*B.lng
return {lat, lng}
}


But obviously, the earth is NOT flat. Furthermore, I am not sure if I can just assume that LatLng could be assumed as cartesian points directly

• Your suspicions are reasonable; you cannot work directly with LatLng to determine the distance between two points on the earth. Of course, it's not hard at all to Google the correct formula; here it is in Javascript. Commented Sep 11, 2019 at 18:57
• this depends on the scale you are working in. For car speeds, you are not going to notice a deviation for quite some time. That is, if the Earth were truly spherical. Your biggest source of error will be changes in elevation. Except in certain localized areas, Simple elevation changes will cause errors that are orders of magnitude larger than Flat Earth vs Spherical Earth. Commented Sep 12, 2019 at 3:14