Skip to content

Instantly share code, notes, and snippets.

@av01d
Last active February 22, 2024 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save av01d/f7f97cf1217945fc4628c6c97e916122 to your computer and use it in GitHub Desktop.
Save av01d/f7f97cf1217945fc4628c6c97e916122 to your computer and use it in GitHub Desktop.
Javascript Point2PointBearing: Caculate bearing between 2 lat/lng points
/**
* Calculate bearing (in degrees, 0-360) between two lat/lng points.
*/
const Point2PointBearing = (lat1, lng1, lat2, lng2) => {
const toRad = num => num * Math.PI / 180;
const toDeg = num => num * 180 / Math.PI;
lat1 = toRad(lat1);
lng1 = toRad(lng1);
lat2 = toRad(lat2);
lng2 = toRad(lng2);
const y = Math.sin(lng2 - lng1) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) * Math.cos(lng2 - lng1);
const brng = toDeg(Math.atan2(y, x));
return (brng + 360) % 360;
}
//console.log(Point2PointBearing(52.25,5.77,52.35,5.95))
@av01d
Copy link
Author

av01d commented Feb 21, 2024

Example: console.log(Point2PointBearing(52.25,5.77,52.35,5.95))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment