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.
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
def haversine(lat1, long1, lat2, long2) | |
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 = power(Math::sin(dlat/2), 2) + Math::cos(rlat1) * Math::cos(rlat2) * power(Math::sin(dlon/2), 2) | |
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a)) | |
d = r * c | |
return d | |
end |
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.
Hey. You are using a function called power which isnt part of ruby. Care you include it here?
ReplyDeleteThanks!
Hi,
DeleteSorry about that.
Here's the power function:
def power(num, pow)
num ** pow
end
For that function, what do you make num and pow equal to as I can't get my head around it. The line is -
ReplyDeletea = 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.
Hi,
DeleteThe 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)
Just found a slightly different implementation which does the powers manually, would this work instead?
ReplyDeletea = (Math.sin(dlat_rad/2))**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * (Math.sin(dlon_rad/2))**2
Many thanks.
I prefer typically the present. It is terrific to realize a man or woman verbalize from your very own cardiovascular system in addition to good utilizing this fundamental topic may well be readily perceived. UKdistance
ReplyDelete