Last active
February 22, 2024 09:33
-
-
Save av01d/f7f97cf1217945fc4628c6c97e916122 to your computer and use it in GitHub Desktop.
Javascript Point2PointBearing: Caculate bearing between 2 lat/lng points
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
console.log(Point2PointBearing(52.25,5.77,52.35,5.95))