Skip to content

Instantly share code, notes, and snippets.

@afrase
Forked from matthutchinson/distance_away_report.rb
Last active November 8, 2019 16:48
Show Gist options
  • Save afrase/9fa86925ac67fe7186df8599b9edc30b to your computer and use it in GitHub Desktop.
Save afrase/9fa86925ac67fe7186df8599b9edc30b to your computer and use it in GitHub Desktop.
Ruby script for the find distance between two points using haversine formula
RAD_PER_DEG = 0.017453293
Rmiles = 3956
def haversine_distance(lat1, lon1, lat2, lon2)
dlon = lon2 - lon1
dlat = lat2 - lat1
dlon_rad = dlon * RAD_PER_DEG
dlat_rad = dlat * RAD_PER_DEG
lat1_rad = lat1 * RAD_PER_DEG
lon1_rad = lon1 * RAD_PER_DEG
lat2_rad = lat2 * RAD_PER_DEG
lon2_rad = lon2 * RAD_PER_DEG
a = (Math.sin(dlat_rad / 2)) ** 2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * (Math.sin(dlon_rad / 2)) ** 2
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
Rmiles * c
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment