Javascript + Maths - get bearing of point A from B as shown on a standard map

138 views Asked by At

Using the below formula, I can get the bearing between two locations on a globe, but when that angle is used to show the direction between two points on a EPSG:3857 (Mercator) map, the angle is sometimes off by a few degrees, causing the icon to point in the wrong direction.

(Math.atan2(b.y - a.y, b.x - a.x) * 180 / Math.PI)

For example, if I draw a line on my map between two locations and place an icon next to it (direction computed using said function), you can see the issue: the icon should be rotated a few degrees more clockwise. I believe this is caused by the curvature of the earth, because depending on the locations of the points, the angle is off by different amounts.

enter image description here

1

There are 1 answers

0
Benjamin Sommer On

I was able to resolve this by using the below formula:

function bearing(startLat, startLng, destLat, destLng) {
  return ((Math.atan2(0,1) - Math.atan2((destLat - startLat),(destLng - startLng)))*180/Math.PI+180) - 85
}