PHP 循环遍历 GPX 以计算轨道的总距离


PHP Looping through a GPX to calculate total distance of a track

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

我真的在努力(仍在学习)将其带入下一阶段,即获取两组经纬度值,将其添加到总距离变量中,然后循环到下一组值。有人可以用 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)

?>

这能回答你的问题吗?

<?
$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;
?>