Skip to content

Instantly share code, notes, and snippets.

@jeanfbrito
Last active May 18, 2020 22:15
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 jeanfbrito/9b731de5da9a1103e656c423761ef3de to your computer and use it in GitHub Desktop.
Save jeanfbrito/9b731de5da9a1103e656c423761ef3de to your computer and use it in GitHub Desktop.

Executing the code:

ruby distance_calculator.rb

To edit the points, modify the array location_points

location_points = [
[-29.640088, -50.764216],
[-29.637486, -50.770814],
[-29.633196, -50.773013]
]
# using Harvesine formula to calculate the distance
# based on https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/calculations.rb#L72
def distance(location_one, location_two)
rad_per_deg = Math::PI/180
radius_in_kilometers = 6371
radius_in_meters = radius_in_kilometers * 1000
dlat_rad = (location_two[0]-location_one[0]) * rad_per_deg
dlon_rad = (location_two[1]-location_one[1]) * rad_per_deg
latitude_one_rad, lon1_rad = location_one.map {|i| i * rad_per_deg }
latitude_two_rad, lon2_rad = location_two.map {|i| i * rad_per_deg }
a = Math.sin(dlat_rad/2)**2 + Math.cos(latitude_one_rad) * Math.cos(latitude_two_rad) * Math.sin(dlon_rad/2)**2
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a))
radius_in_meters * c # Delta in meters
end
location_points.each_with_index do |initial_point, initial_index|
puts "Distance from the point #{initial_index} to \n"
location_points.each_with_index do |point, index|
if index != initial_index
puts "point #{index} is #{distance(initial_point, point).to_i} meters"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment