PHP通过GPX循环计算轨道的总距离

时间:2015-01-24 10:16:57

标签: php xml loops gpx

我想通过gpx文件循环并计算总距离。我有一个函数可以计算两组lat长点之间的距离,我已经设置了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)


?>

1 个答案:

答案 0 :(得分:2)

这是否回答了你的问题?

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