Skip to content

Instantly share code, notes, and snippets.

@olistik
Created April 26, 2017 07:50
Show Gist options
  • Save olistik/56ddc6b1efa91920ee3530ae511597e0 to your computer and use it in GitHub Desktop.
Save olistik/56ddc6b1efa91920ee3530ae511597e0 to your computer and use it in GitHub Desktop.
Haversine formula to calculate the distance between two points.
module Geo
class Point
attr_accessor :latitude, :longitude
def initialize(latitude:, longitude:)
self.latitude = latitude
self.longitude = longitude
end
end
def self.radians(degrees)
degrees * Math::PI / 180
end
class Distance
# https://en.wikipedia.org/wiki/Geographical_distance
EARTH_RADIUS_KM = 6371
def initialize(p1:, p2:)
self.p1 = p1
self.p2 = p2
end
def value
rad_lat1 = ::Geo.radians(p1.latitude)
rad_lat2 = ::Geo.radians(p2.latitude)
lat_half = (rad_lat2 - rad_lat1) / 2
lon_half = Math::PI * (p2.longitude - p1.longitude) / 360
a = Math.sin(lat_half)
a *= a
b = Math.sin(lat_half)
b *= b * Math.cos(rad_lat1) * Math.cos(rad_lat2)
central_angle = 2 * Math.atan2(Math.sqrt(a + b), Math.sqrt(1 - a - b))
EARTH_RADIUS_KM * central_angle
end
private
attr_accessor :p1, :p2
end
end
p1 = Geo::Point.new(latitude: 42.8256, longitude: 13.7152)
p2 = Geo::Point.new(latitude: 42.8245, longitude: 13.7165)
distance = Geo::Distance.new(p1: p1, p2: p2)
distance.value # => 0.1516858383219569
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment