Created
March 29, 2013 01:15
-
-
Save timols/5268103 to your computer and use it in GitHub Desktop.
Ruby implementation of the haversine distance 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
## | |
# Haversine Distance Calculation | |
# | |
# Accepts two coordinates in the form | |
# of a tuple. I.e. | |
# geo_a Array(Num, Num) | |
# geo_b Array(Num, Num) | |
# miles Boolean | |
# | |
# Returns the distance between these two | |
# points in either miles or kilometers | |
def haversine_distance(geo_a, geo_b, miles=false) | |
# Get latitude and longitude | |
lat1, lon1 = geo_a | |
lat2, lon2 = geo_b | |
# Calculate radial arcs for latitude and longitude | |
dLat = (lat2 - lat1) * Math::PI / 180 | |
dLon = (lon2 - lon1) * Math::PI / 180 | |
a = Math.sin(dLat / 2) * | |
Math.sin(dLat / 2) + | |
Math.cos(lat1 * Math::PI / 180) * | |
Math.cos(lat2 * Math::PI / 180) * | |
Math.sin(dLon / 2) * Math.sin(dLon / 2) | |
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) | |
d = 6371 * c * (miles ? 1 / 1.6 : 1) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!