Skip to content

Instantly share code, notes, and snippets.

@rogerrohrbach
Created July 3, 2010 19:51
Show Gist options
  • Save rogerrohrbach/462790 to your computer and use it in GitHub Desktop.
Save rogerrohrbach/462790 to your computer and use it in GitHub Desktop.
Calculate the distance between two points on Earth
module Geo
def self.distance(point_a = {}, point_b = {})
# http://en.wikipedia.org/wiki/Haversine_formula
r = 6371.009 # IUGG mean radius of the Earth
deg2rad = lambda { |d| d * Math::PI / 180 }
sin2 = lambda { |x| Math.sin(x) ** 2 }
lat1 = deg2rad.call(point_a['lat'])
lat2 = deg2rad.call(point_b['lat'])
dlat = lat2 - lat1
dlng = deg2rad.call(point_b['lng']) - deg2rad.call(point_a['lng'])
r * 2 *
Math.asin(
Math.sqrt(
sin2.call(dlat / 2) + Math.cos(lat1) *
Math.cos(lat2) * sin2.call(dlng / 2)
)
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment