如何计算GPX文件的距离?

时间:2009-02-20 15:28:48

标签: xml algorithm gps gpx

我有GPX file的GPS轨道。现在我想计算一下这条赛道所覆盖的距离。

计算这个的最佳方法是什么?

5 个答案:

答案 0 :(得分:24)

计算两点(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(1-@a))
    select @d = @R * @c

    return @d 
end

以千里为单位返回距离。对于公里数,将地球半径替换为等效公里数。

Here是一个更深入的解释。

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

可以找到Vincenty formulae的Delphi实现here

答案 3 :(得分:1)

这是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
  }
}

答案 4 :(得分:0)

这个问题相当陈旧,但我想为完整性添加一个python选项。 GeoPy同时包含great-circle distanceVincenty distance