Skip to content

Instantly share code, notes, and snippets.

@cirops
Created May 24, 2018 08:22
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 cirops/984cbca7b53d22d43d7dc6aad5f4d2bb to your computer and use it in GitHub Desktop.
Save cirops/984cbca7b53d22d43d7dc6aad5f4d2bb to your computer and use it in GitHub Desktop.
# Calculates geometric distances between all given points
# coordinates are passed as arguments, as in the following sample:
# ruby geodistance.rb 62.425,52.424 42.0,90.5256 0.0,0.0 90.0,-180.0
# returns the distance in kilometers
##
# Haversine Distance Calculation Function
#
# by https://gist.github.com/timols/5268103
# Accepts two coordinates in the form
# of a tuple. I.e.
# geo_a Array(Num, Num)
# geo_b Array(Num, Num)
# miles Boolean
#
# Returns the distance between these two
# points in either miles or kilometers
def haversine_distance(geo_a, geo_b, miles=false)
# Get latitude and longitude
lat1, lon1 = geo_a
lat2, lon2 = geo_b
# Calculate radial arcs for latitude and longitude
dLat = (lat2 - lat1) * Math::PI / 180
dLon = (lon2 - lon1) * Math::PI / 180
a = Math.sin(dLat / 2) *
Math.sin(dLat / 2) +
Math.cos(lat1 * Math::PI / 180) *
Math.cos(lat2 * Math::PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2)
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
d = 6371 * c * (miles ? 1 / 1.6 : 1)
end
raise "Must specify at least two points! (e.g. 62.425,52.424 42.0,90.5256" if ARGV.length < 2
points = []
i = 0
loop do
lat, long = ARGV[i].split(",")
lat = lat.to_f
long = long.to_f
raise "Coordinate ##{i+1} malformed" if (lat < -90 or lat > 90 or long < -180 or long > 180)
points.push([lat,long])
i += 1
break if i == ARGV.length
end
for i in 0..points.size do
for j in i+1..points.size-1 do
puts " #{points[i]} <-> #{points[j]} = #{haversine_distance(points[i], points[j])}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment