Wednesday, April 11, 2012

Calculating distance between two points in Ruby with the Haversine formula

I recently needed to calculate the distance between two points (lat/long) in Ruby (reading a .gpx file, and finding the distance between each point).
After a quick search on stackoverflow.com I found the following post http://stackoverflow.com/questions/569980/how-to-calculate-distance-from-a-gpx-file.

Below is my Ruby version of the formula shown in the second post:


This will calculate in meters. To get KM, remove "*1000" on line 3. To get miles, change line 3 to "r = 3959". I'll post the whole GPX parse code in a few days.