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



I want loop though a gpx file and calculate the total distance. I have a function that can calc the distance between two sets of lat long points and I've set up simplexml to read & loop through the gpx file trkseg points.


I am really struggling (still learning) to take it to the next stage of getting two sets of lat long values adding it to a total distance var and then looping to the next set of values. Can someone point me in the right direction with the 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)


?>

No comments:

Post a Comment