Created
November 11, 2010 23:20
-
-
Save j05h/673425 to your computer and use it in GitHub Desktop.
Haversine formula (http://en.wikipedia.org/wiki/Haversine_formula) in Ruby
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
class Numeric | |
def to_rad | |
self * Math::PI / 180 | |
end | |
end | |
# http://www.movable-type.co.uk/scripts/latlong.html | |
# loc1 and loc2 are arrays of [latitude, longitude] | |
def distance loc1, loc2 | |
lat1, lon1 = loc1 | |
lat2, lon2 = loc2 | |
dLat = (lat2-lat1).to_rad; | |
dLon = (lon2-lon1).to_rad; | |
a = Math.sin(dLat/2) * Math.sin(dLat/2) + | |
Math.cos(lat1.to_rad) * Math.cos(lat2.to_rad) * | |
Math.sin(dLon/2) * Math.sin(dLon/2); | |
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); | |
d = 6371 * c; # Multiply by 6371 to get Kilometers | |
end |
Ended up using the Haversine gem -- same results, but easier to use on my project.
Borrowed this for an example in our server monitoring tools.
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this helped me with an infovis project.