Last active
April 6, 2021 19:07
-
-
Save aflansburg/0e03cce57045acecd9d37025dd132035 to your computer and use it in GitHub Desktop.
Haversine - Straight Line Distance Between Two Sets of Geographical Coordinates (Latitude, Longitude)
This file contains hidden or 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
# radius of earth in meters | |
R = 6371000; | |
def haversine(coord1:, coord2:) | |
# first add our own radians function since Ruby Math does not have one | |
radians = -> (degrees) { degrees * (Math::PI / 180)} | |
# convert latitude degrees to radians | |
phi_1 = radians.call(coord1[:latitude]); | |
phi_2 = radians.call(coord2[:latitude]); | |
# delta being the "difference" between the latitudes and longitudes of each coordinate set expressed | |
# in radians | |
delta_phi = radians.call(coord2[:latitude] - coord1[:latitude]); | |
delta_lambda = radians.call(coord2[:longitude] - coord1[:longitude]); | |
# sin²(φB - φA/2) + cos φA * cos φB * sin²(λB - λA/2) | |
a = Math.sin(delta_phi/2.0)**2 + Math.cos(phi_1) * Math.cos(phi_2) * Math.sin(delta_lambda/2.0)**2; | |
# 2 * atan2( √a, √(1−a) ) | |
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
meters = R * c; | |
kilometers = meters / 1000.0; | |
miles = kilometers / 1.609344; | |
{ meters: meters, kilometers: kilometers, miles: miles } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment