Created
January 13, 2016 15:13
-
-
Save jamiedumont/26488a4293f81e2ffbde to your computer and use it in GitHub Desktop.
High performance JS function to return distance between two points using Haversine formula
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 distance(lat1, lon1, lat2, lon2) { | |
var deg2rad = Math.PI / 180; | |
lat1 *= deg2rad; | |
lon1 *= deg2rad; | |
lat2 *= deg2rad; | |
lon2 *= deg2rad; | |
var diam = 12742; // Diameter of the earth in km (2 * 6371) | |
var dLat = lat2 - lat1; | |
var dLon = lon2 - lon1; | |
var a = ( | |
(1 - Math.cos(dLat)) + | |
(1 - Math.cos(dLon)) * Math.cos(lat1) * Math.cos(lat2) | |
) / 2; | |
return diam * Math.asin(Math.sqrt(a)); | |
} | |
distance(48, -122, 49, -121); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tested on Chrome 47.0.2526.106 on Mac OS X 10.11.2 to perform ~7.4million ops/sec as of 12-01-16