【问题标题】:PHP Looping through a GPX to calculate total distance of a trackPHP循环通过GPX以计算轨道的总距离
【发布时间】:2015-03-23 08:22:55
【问题描述】:

我想通过一个 gpx 文件循环并计算总距离。我有一个函数可以计算两组 lat long 点之间的距离,并且我设置了 simplexml 来读取和循环遍历 gpx 文件 trkseg 点。

我真的很努力(仍在学习)将其带到下一个阶段,即获取两组 lat long 值,将其添加到总距离 var 中,然后循环到下一组值。有人可以用 PHP 为我指明正确的方向吗?

<?php
// Funcntion for calculating distance between to sets of lat/long points

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
  return ($miles * 0.8684);
} else {
    return $miles;
  }
}



// Read GPX file, find track lat/lon attributes and loop

$xml=simplexml_load_file("mygpxfile.gpx");

echo $xml->trk->name;
echo "<br>";

foreach( $xml->trk->trkseg->{'trkpt'} as $trkpt ) {

    $trkptlat = $trkpt->attributes()->lat;
    $trkptlon = $trkpt->attributes()->lon;
    }

// How do I use the function above to now loop through all the values to calc total distance?

// $total_distance = distance($lat1, $lon1, $lat2, $lon2, $unit)


?>

【问题讨论】:

    标签: php xml loops gpx


    【解决方案1】:

    这是否回答了您的问题?

    <?
    $last_lat = false;
    $last_lon = false;
    $total_distance = 0;
    foreach( $xml->trk->trkseg->{'trkpt'} as $trkpt ) {
        $trkptlat = $trkpt->attributes()->lat;
        $trkptlon = $trkpt->attributes()->lon;
        if($last_lat){
            $total_distance+=distance($trkptlat, $trkptlon, $last_lat, $last_lon, 'k');
        }
        $last_lat = $trkptlat;
        $last_lon = $trkptlon;
    }
    echo $total_distance;
    ?>
    

    【讨论】:

    • 谢谢,我可以看到它是如何工作的。我收到警告:警告:deg2rad() 期望参数 1 为双倍,对象在第 24 行的 xml.php 中给出 第 24 行:$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));这和设置变量类型有关吗?
    猜你喜欢
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多