Calculate bearing between 2 points with javascript

Rogier picture Rogier · Oct 5, 2017 · Viewed 7.4k times · Source

I want to calculate the bearing from point 1 to point 2 The input format is 52.070564 - 4.407116

No matter what i try i cannot get an correct output.

The formula i use is :

Answer

Andrey Bulgakov picture Andrey Bulgakov · Aug 29, 2018

You can calculate bearing using this functions:

// Converts from degrees to radians.
function toRadians(degrees) {
  return degrees * Math.PI / 180;
};
 
// Converts from radians to degrees.
function toDegrees(radians) {
  return radians * 180 / Math.PI;
}


function bearing(startLat, startLng, destLat, destLng){
  startLat = toRadians(startLat);
  startLng = toRadians(startLng);
  destLat = toRadians(destLat);
  destLng = toRadians(destLng);

  y = Math.sin(destLng - startLng) * Math.cos(destLat);
  x = Math.cos(startLat) * Math.sin(destLat) -
        Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
  brng = Math.atan2(y, x);
  brng = toDegrees(brng);
  return (brng + 360) % 360;
}