Created
January 21, 2014 00:11
-
-
Save JulienMelissas/8531978 to your computer and use it in GitHub Desktop.
Using the Haversine formula to calculate the distance between 2 points in JS. CHECK IT OUT IN YOUR CONSOLE
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
<html> | |
<head> | |
<title>Haversine Test</title> | |
</head> | |
<body> | |
<script> | |
myLoc = { | |
lat: 35.597982, | |
lng: -82.551416 | |
}; | |
thePoint = { | |
lat: 35.253467, | |
lng: -82.706852 | |
}; | |
rad = function(x) {return x*Math.PI/180;} | |
distHaversine = function(p1, p2) { | |
var R = 3960; // earth's mean radius in mi | |
var dLat = rad(p2.lat - p1.lat); | |
var dLong = rad(p2.lng - p1.lng); | |
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) * Math.sin(dLong/2) * Math.sin(dLong/2); | |
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); | |
var d = R * c; | |
return d.toFixed(1); | |
} | |
console.log(distHaversine(myLoc, thePoint)); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment