Created
March 9, 2013 08:04
-
-
Save madpilot/5123414 to your computer and use it in GitHub Desktop.
Ruby haversine - finds the distance between to long/lats. Can be used as a paramater for sort.
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
def haversine(x, y) | |
r = 6371 | |
lat1 = x.latitude | |
lat2 = y.latitude | |
lon1 = x.longitude | |
lon2 = y.longitude | |
d_lat = (lat2 - lat1) * Math::PI / 180 | |
d_lon = (lon2 - lon1) * Math::PI / 180 | |
lat1 = lat1 * Math::PI / 180 | |
lat2 = lat2 * Math::PI / 180 | |
a = (Math.sin(d_lat / 2) * Math.sin(d_lat / 2)) + (Math.sin(d_lon / 2) | |
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) | |
r * c | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment