Skip to content

Instantly share code, notes, and snippets.

@madpilot
Created March 9, 2013 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madpilot/5123414 to your computer and use it in GitHub Desktop.
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.
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