Created
September 6, 2013 10:50
-
-
Save Witiko/6462295 to your computer and use it in GitHub Desktop.
A function that calculates the distance, gradient and bearing of a path between two points on the Earth. Requires the Math.js library because of the Number.prototype.* calls.
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
function Points(lat1, lon1, alt1, | |
lat2, lon2, alt2) { | |
alt1 = alt1 / 1000 || 0; | |
alt2 = alt2 / 1000 || 0; | |
var dLat = (lat2 - lat1).degToRad(), | |
dLon = (lon2 - lon1).degToRad(), | |
dAlt = alt2 - alt1; | |
lat1 = lat1.degToRad(); | |
lat2 = lat2.degToRad(); | |
lon1 = lon1.degToRad(); | |
lon2 = lon2.degToRad(); | |
var a = (dLat / 2).sin().pow() + | |
(dLon / 2).sin().pow() * lat1.cos() | |
* lat2.cos(), | |
Bx = lat2.cos() * dLon.cos(), | |
By = lat2.cos() * dLon.sin(), | |
gDist = 12742 * a.rt().atan2((1 - a).rt()); | |
this.midPoint = [ | |
Math.atan2(lat1.sin() + lat2.sin(), | |
((lat1.cos() + Bx) * | |
(lat1.cos() + Bx) + By.pow()).rt()).radToDeg(), | |
(lon1 + By.atan2(lat1.cos() + Bx)).radToDeg(), | |
Math.avg(alt1, alt2) | |
]; | |
this.distance = Math.sqrt(gDist.pow() + dAlt.pow()); | |
this.gradient = Math.acos( | |
12742 * a.rt().atan2((1 - a).rt()) / this.distance | |
).radToDeg(); | |
this.initBearing = (( | |
dLon.sin() * lat2.cos() | |
).atan2( | |
lat1.cos() * lat2.sin() - | |
lat1.sin() * lat2.cos() * dLon.cos() | |
).radToDeg()).degAdjust(); | |
this.finalBearing = (( | |
(-dLon).sin() * lat1.cos() | |
).atan2( | |
lat2.cos() * lat1.sin() - | |
lat2.sin() * lat1.cos() * (-dLon).cos() | |
).radToDeg() + 180).degAdjust(); | |
lat1 = this.midPoint[0].degToRad(); | |
lat2 = lat2; | |
dLon = (lon2.radToDeg() - this.midPoint[1]).degToRad(); | |
this.bearing = (( | |
dLon.sin() * lat2.cos() | |
).atan2( | |
lat1.cos() * lat2.sin() - | |
lat1.sin() * lat2.cos() * dLon.cos() | |
).radToDeg()).degAdjust(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment