From 892eab89d7429ba6d955d2f51f111e082457aabe Mon Sep 17 00:00:00 2001
From: Alex Reisner <alex@alexreisner.com>
Date: Wed, 15 Apr 2009 23:47:46 -0400
Subject: [PATCH] Add Geocoder.distance_between class method.

---
 lib/geocoder.rb | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/lib/geocoder.rb b/lib/geocoder.rb
index a2b1c350..f8a5091e 100644
--- a/lib/geocoder.rb
+++ b/lib/geocoder.rb
@@ -40,6 +40,29 @@ module Geocoder
     end
   end
 
+  ##
+  # Calculate the distance between two points (Haversine formula).
+  #
+  def self.distance_between(lat1, lon1, lat2, lon2, options = {})
+    # set default options
+    options[:units] ||= :mi
+    # define available units
+    units = { :mi => 3956, :km => 6371 }
+    
+    # convert degrees to radians
+    lat1 *= Math::PI / 180
+    lon1 *= Math::PI / 180
+    lat2 *= Math::PI / 180
+    lon2 *= Math::PI / 180
+    dlat = (lat1 - lat2).abs
+    dlon = (lon1 - lon2).abs
+
+    a = (Math.sin(dlat / 2))**2 + Math.cos(lat1) *
+        (Math.sin(dlon / 2))**2 * Math.cos(lat2)  
+    c = 2 * Math.atan2( Math.sqrt(a), Math.sqrt(1-a))  
+    c * units[options[:units]]
+  end
+  
   ##
   # Find all records within a radius (in miles) of the given point.
   # Taken from excellent tutorial at:
-- 
GitLab