Created
April 27, 2013 17:05
-
-
Save vasrap/5473795 to your computer and use it in GitHub Desktop.
Calculates the distance in meters between 2 GPS coordinates using the haversine formula
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Calculates the distance in meters between 2 GPS coordinates | |
# http://en.wikipedia.org/wiki/Haversine_formula | |
# Arguments p1, p2 are instances of the class Point below: | |
# class Point | |
# attr_accessor :lat, :lon | |
# end | |
def haversine_distance(p1, p2) | |
lat1 = p1.lat | |
long1 = p1.lon | |
lat2 = p2.lat | |
long2 = p2.lon | |
dtor = Math::PI / 180 | |
r = 6378.14 * 1000 | |
rlat1 = lat1 * dtor | |
rlong1 = long1 * dtor | |
rlat2 = lat2 * dtor | |
rlong2 = long2 * dtor | |
dlon = rlong1 - rlong2 | |
dlat = rlat1 - rlat2 | |
a = (Math.sin(dlat / 2)**2) + Math.cos(rlat1) * Math.cos(rlat2) * (Math.sin(dlon / 2)**2) | |
c = 2 * Math.atan2(Mat.sqrt(a), Math.sqrt(1 - a)) | |
d = r * c | |
d | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment