如何计算GPX文件的距离?

如何计算GPX文件的距离?

问题描述:

我有一个GPX file与GPS轨道。现在我想计算我用这个轨道覆盖的距离。如何计算GPX文件的距离?

什么是最好的计算方法?

计算两点之间距离(​​GPX文件中的每对航点)的传统方法是使用Haversine公式。

我有一个实现算法的SQL Server函数。这应该很容易翻译成其他语言:

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([email protected])) 
    select @d = @R * @c 

    return @d 
end 

这将返回以英里为单位的距离。对于公里,将地球半径替换为相当于km的公里。

Here是一个更深入的解释。

编辑:此功能足够快且足够准确,可以使用邮政编码数据库进行半径搜索。多年来,它一直在this site上做得很好(但现在不再这样做了,因为链接现在已被破坏)。

+0

非常感谢。我将把它移植到java并发布到这里。 @DtoR是什么意思?到半径的距离? – guerda 2009-02-20 16:34:38

+1

这是将度数转换为Radians pi/180的因素。 – cdonner 2009-02-21 00:23:33

Mike Gavaghan has an algorithm在他的网站上进行距离计算。有一个C#和一个JAVA版本的代码。

德尔福执行Vincenty formulae可以找到here

这是一个Scala实现。

3958.761是以英里为单位的mean radius of the Earth。要在km(或其他单位)中得到结果,只需更改此数字即可。

// The Haversine formula 
def haversineDistance(pointA: (Double, Double), pointB: (Double, Double)): Double = { 
    val deltaLat = math.toRadians(pointB._1 - pointA._1) 
    val deltaLong = math.toRadians(pointB._2 - pointA._2) 
    val a = math.pow(math.sin(deltaLat/2), 2) + math.cos(math.toRadians(pointA._1)) * math.cos(math.toRadians(pointB._1)) * math.pow(math.sin(deltaLong/2), 2) 
    val greatCircleDistance = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) 
    3958.761 * greatCircleDistance 
} 

// A sequence of gpx trackpoint lat,long pairs parsed from the track GPX data 
val trkpts: Seq[(Double, Double)] = { 
    val x = scala.xml.XML.loadString(track) 
    (x \\ "trkpt").map(trkpt => ((trkpt \ "@lat").text.toDouble, (trkpt \ "@lon").text.toDouble)) 
} 

// Distance of track in miles using Haversine formula 
val trackDistance: Double = { 
    trkpts match { 
    case head :: tail => tail.foldLeft(head, 0.0)((accum, elem) => (elem, accum._2 + haversineDistance(accum._1, elem)))._2 
    case Nil => 0.0 
    } 
} 

这个问题是相当老,但我想添加一个python选项的完整性。 GeoPy既有great-circle distance也有Vincenty distance