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.

5 comments:

  1. Hey. You are using a function called power which isnt part of ruby. Care you include it here?

    Thanks!

    ReplyDelete
    Replies
    1. Hi,

      Sorry about that.

      Here's the power function:

      def power(num, pow)
      num ** pow
      end

      Delete
  2. For that function, what do you make num and pow equal to as I can't get my head around it. The line is -

    a = power(Math::sin(dlat/2), 2) + Math::cos(rlat1) * Math::cos(rlat2) * power(Math::sin(dlon/2), 2)

    Just confused as to what to declare num and pow as in this instance.

    Any help appreciated.

    ReplyDelete
    Replies
    1. Hi,

      The power method takes a number and the power, and returns number**power, just as you've described in your other comment.

      If you are doing this in Ruby, I'd recommend checking out the geo_magic gem (https://github.com/kristianmandrup/geo_magic)

      Delete
  3. Just found a slightly different implementation which does the powers manually, would this work instead?

    a = (Math.sin(dlat_rad/2))**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * (Math.sin(dlon_rad/2))**2

    Many thanks.

    ReplyDelete