Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
978 views
in Technique[技术] by (71.8m points)

xml - How to calculate distance from a GPX file?

I have a GPX file with a GPS track. Now I want to calculate the distance I covered with this track.

What's the best way to calculate this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The traditional way of calculating the distance between two points (each pair of waypoints in your GPX file) is with the Haversine formula.

I have a SQL Server function that implements the algorithm. This should be easy to translate into other languages:

create function dbo.udf_Haversine(@lat1 float, @long1 float, 
                   @lat2 float, @long2 float) returns float begin
    declare @dlon float, @dlat float, @rlat1 float, 
                 @rlat2 float, @rlong1 float, @rlong2 float, 
                 @a float, @c float, @R float, @d float, @DtoR float

    select @DtoR = 0.017453293
    select @R = 3959      -- Earth radius

    select 
        @rlat1 = @lat1 * @DtoR,
        @rlong1 = @long1 * @DtoR,
        @rlat2 = @lat2 * @DtoR,
        @rlong2 = @long2 * @DtoR

    select 
        @dlon = @rlong1 - @rlong2,
        @dlat = @rlat1 - @rlat2

    select @a = power(sin(@dlat/2), 2) + cos(@rlat1) * 
                     cos(@rlat2) * power(sin(@dlon/2), 2)
    select @c = 2 * atn2(sqrt(@a), sqrt(1-@a))
    select @d = @R * @c

    return @d 
end

This returns the distance in Miles. For kilometers, replace the earth radius with it's km equivalent.

Here is a more in-depth explanation.

Edit: This function is fast enough and accurate enough for doing radius searches with a ZIP code database. It has been doing a great job on this site for years (but it no longer does, as the link is broken now).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...