From 2b7e5411733f8878809018a794db829548f43b84 Mon Sep 17 00:00:00 2001 From: Alex Reisner <alex@alexreisner.com> Date: Thu, 24 Mar 2011 20:00:29 -0400 Subject: [PATCH] Add calculations for distances btwn lat/lon lines. --- lib/geocoder/calculations.rb | 15 +++++++++++++++ test/geocoder_test.rb | 12 ++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/geocoder/calculations.rb b/lib/geocoder/calculations.rb index d9333d80..bc97d3b8 100644 --- a/lib/geocoder/calculations.rb +++ b/lib/geocoder/calculations.rb @@ -21,6 +21,21 @@ module Geocoder # KM_IN_MI = 0.621371192 + ## + # Calculate the distance between latitude lines in the given units. + # + def distance_between_latitude_lines(units = :mi) + 2 * Math::PI * earth_radius(units) / 360 + end + + ## + # Calculate the distance between longitude lines at the given latitude. + # This ranges from around 69 miles at the equator to zero at the poles. + # + def distance_between_longitude_lines(latitude, units = :mi) + distance_between_latitude_lines(units) * Math.cos(to_radians(latitude)) + end + ## # Calculate the distance between two points on Earth (Haversine formula). # Takes two sets of coordinates and an options hash: diff --git a/test/geocoder_test.rb b/test/geocoder_test.rb index 5443e64a..91179e41 100644 --- a/test/geocoder_test.rb +++ b/test/geocoder_test.rb @@ -139,6 +139,18 @@ class GeocoderTest < Test::Unit::TestCase # --- calcluations --- + def test_distance_between_longitude_lines_at_equator + assert_equal 69, Geocoder::Calculations.distance_between_longitude_lines(0).round + end + + def test_distance_between_longitude_lines_at_new_york + assert_equal 53, Geocoder::Calculations.distance_between_longitude_lines(40).round + end + + def test_distance_between_longitude_lines_at_north_pole + assert_equal 0, Geocoder::Calculations.distance_between_longitude_lines(89.98).round + end + def test_distance_between assert_equal 69, Geocoder::Calculations.distance_between(0,0, 0,1).round la_to_ny = Geocoder::Calculations.distance_between(34.05,-118.25, 40.72,-74).round -- GitLab