Skip to content

Instantly share code, notes, and snippets.

@affix
Created November 10, 2015 03:03
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 affix/dc12412aa3050d58f805 to your computer and use it in GitHub Desktop.
Save affix/dc12412aa3050d58f805 to your computer and use it in GitHub Desktop.
Calculate the distance between two GPS Co-Ordinates with Ruby
def distance_between(lat1,lon1,lat2,lon2, miles=false)
r = 6371; # Kilometers
dLat = to_radian(lat2-lat1);
dLon = to_radian(lon2-lon1);
lat1 = to_radian(lat1);
lat2 = to_radian(lat2);
a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = r * c;
if(miles)
d = d * 0.62137
end
d
end
def to_radian(input)
input * Math::PI / 180
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment