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 |