Coder Social home page Coder Social logo

sibyx / phpgpx Goto Github PK

View Code? Open in Web Editor NEW
146.0 12.0 51.0 485 KB

Simple library for reading and creating GPX files written in PHP.

Home Page: https://sibyx.github.io/phpGPX/

License: MIT License

PHP 100.00%
php gpx gpx-files php-library composer xml geolocation calculations gps gis

phpgpx's People

Contributors

benlumley avatar joebiker avatar lommes avatar lukey78 avatar luklewluk avatar miqwit avatar neronmoon avatar nono303 avatar ptrupek avatar robertblackwell avatar roynijkamp avatar sandcore-dev avatar sdennler avatar shaydu avatar sibyx avatar uniquexor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpgpx's Issues

typo that lead to error

hello, i notice a typo in
/Models/Extensions/TrackPointExtension.php
here

/**
 * Heart rate in beats per minute.
 * @var float
 */
public $hearthRate; 

that supposed to be

public $heartRate;

because when i try to manually create TrackPointExtension by
new \phpGPX\Models\Extensions\TrackPointExtension;
and then save it, i get

Notice: Undefined property: phpGPX\Models\Extensions\TrackPointExtension::$heartRate in ****\phpGPX\Parsers\Extensions\TrackPointExtensionParser.php on line 88

because code expect heartRate var, not hearthRate.
also this typo create two vars in extenstion, one of it empty

  ["hearthRate"]=>      NULL
  ["heartRate"]=>      float(107)

fix it please

RoutePoints and TripExtensions WIP

I'm offering a patch file for work I did to:

  1. Fix handling of rtept tag
  2. Initial Implementation of the Garmin Trip Extension: parse and toXML, issue a ViaPoint or ShapingPoint extension tag as required

Notes on what I did and caveats:

  • Duplicated the existing extension and modified to support http://www.garmin.com/xmlschemas/TripExtensions/v1
  • Added rtept in Point model and PointParser
  • Modified parsing to allow array of Points. Whitout my changes, only the first point in a route was parsed
  • It seems Routes have rtept and tracks have rtep. I did not manage to handle both tags properly without issuing points twice in toXML: once for rtept, once for rtep. I comment out the undesired tag I want before running the code :-(

Hope this will be helpful and gets properly inserted in the code base.

rtept and Trip Extension WIP.zip

Problem with composer installation

There is a problem while installing through composer.

$ composer require sibyx/phpgpx

[InvalidArgumentException]
Could not find package sibyx/phpgpx.

Did you mean one of these?
sibyx/phpgpx
danmatthews/phpgpx

Error when last trk point does not have a time set

Using RC5

I the first point of a track has a time but that last point does not then the code in Segment.php fails at line 101

if (isset($firstPoint->time) && $firstPoint->time instanceof \DateTime) {
			$this->stats->duration = $lastPoint->time->getTimestamp() - $firstPoint->time->getTimestamp();

			if ($this->stats->duration != 0) {
				$this->stats->averageSpeed = $this->stats->distance / $this->stats->duration;
			}

			if ($this->stats->distance != 0) {
				$this->stats->averagePace = $this->stats->duration / ($this->stats->distance / 1000);
			}
		}

A check is needed to see if $lastpoint->time is set or not.

PS great package - good work

test file
Cedar-Mawdesley-Moss-4ml.gpx.txt

GeoJSON support

Add ability to read/write GeoJSON data files.

GeoJSON is a format for encoding a variety of geographic data structures.

use custom trackpoint extension (in this case: Bad-Elf)?

Not an issue, but a question really.

Can I add/use custom trackpoint extensions?

This so I can read this Bad Elf speed extension:

<trkpt lat="54.315933" lon="-130.325592">
  <ele>49.7</ele>
  <time>2013-06-18T17:02:04Z</time>
  <hdop>1.4</hdop>
  <extensions>
    <badelf:speed>2.006332</badelf:speed>
  </extensions>
</trkpt>

They also have metadata extensions, but I am less interested in those.

        <metadata>
                <extensions>
                        <!-- Name -->
                        <badelf:modelName>Bad Elf GPS Pro</badelf:modelName>
                        <!-- Ser No -->
                        <badelf:modelSerialNumber>118887</badelf:modelSerialNumber>
                        <!-- Model -->
                        <badelf:modelNumber>BE-GPS-2200</badelf:modelNumber>
                        <!-- Hardware Revision -->
                        <badelf:modelHardwareRevision>2.0.0</badelf:modelHardwareRevision>
                        <!-- Firmware Revision -->
                        <badelf:modelFirmwareRevision>2.0.48</badelf:modelFirmwareRevision>
                </extensions>
        </metadata>

Namespace:

<gpx xmlns="http://www.topografix.com/GPX/1/1"
                xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
                xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
                xmlns:badelf="http://bad-elf.com/xmlschemas"
                version="1.1"
                creator="Bad Elf GPS Pro 2.0.48"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd http://bad-elf.com/xmlschemas http://bad-elf.com/xmlschemas/GpxExtensionsV1.xsd">

minAltitude seems to be missing/null if any points do not have an elev tag

When I process the attached file the minAltitude seems to be missing or null in the stats object

  1. Library version 1.0-RC5
  2. PHP version 7.0
  3. Detailed problem description

After processing the attached file, where some of the track points do not have elevations defined, the minAltitude is then missing in the track->stats object.
The code should ignore points without elevations.

Venachar.gpx.txt

PS thanks for otherwise great code, very useful.

cumulativeElevationLoss is missing in stats

Problem description

  1. v1,0RC5
  2. PHP 7
  3. cumulative elevation loss is missing in stats.

For example, when I calculate the stats of a GPX file, I get this answer:

[{"description":"Osterrunde um Bergen-Vogtland.gpx","distance":20843.2107222357080900110304355621337890625,"avgSpeed":0.98572762933249979955263597730663605034351348876953125,"avgPace":1014.4790206166434245460550300776958465576171875,"minAltitude":444.1000000000000227373675443232059478759765625,"maxAltitude":601,"cumulativeElevationGain":370.7000000000001591615728102624416351318359375,"startedAt":"2020-04-12T00:41:05+00:00","finishedAt":"2020-04-12T06:33:30+00:00","duration":21145}]'

It is also missing in this document: https://github.com/Sibyx/phpGPX/blob/69846b781000c12c15eea26c2808fe67f0305802/docs/phpGPX-Models-Stats.md

Expected behaviour

[{"description":"Osterrunde um Bergen-Vogtland.gpx","distance":20843.2107222357080900110304355621337890625,"avgSpeed":0.98572762933249979955263597730663605034351348876953125,"avgPace":1014.4790206166434245460550300776958465576171875,"minAltitude":444.1000000000000227373675443232059478759765625,"maxAltitude":601,"cumulativeElevationGain":370.7000000000001591615728102624416351318359375,"cumulativeElevationLoss":370.7000000000001591615728102624416351318359375,"startedAt":"2020-04-12T00:41:05+00:00","finishedAt":"2020-04-12T06:33:30+00:00","duration":21145}]'

Possible solution

A possible solution if you have any.

Something interesting or funny

Joke or interesting fact to made readers better day :) For example: Ants get drunk and act silly, causing their friend-ants to throw them in puddles of water.

Checklist

Put x into brackets if true.

[x ] PHP version I use
[ x] Package version I use

Tag a new version

Hey there, first I wanted to say thank you for this really nice library.

I noticed that the master branch is about 34 commits ahead as the last tagged version (1.0-RC5).
Could please tag a new version so we can have all the new features and bug fixes from the master branch?

Empty array on load route

Hi,
I was successfully load an array of waypoints and tracks, but failed with routes gpx file with a simple codes. Array points of route is empty.

use phpGPX\phpGPX;
$gpx = new phpGPX();
$file = $gpx->load('gps_result.gpx');
print_r($file);

By the way, thank you for your great work.

Regards,
M

unexpected 'class' (T_CLASS), expecting identifier

Problem description

I get the following error:
Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in vendor/sibyx/phpgpx/src/phpGPX/Models/Track.php on line 51

Code snippet you use

<?php
use phpGPX\phpGPX;

$gpx = new phpGPX();

$file = $gpx->load('scripts/example.gpx');

foreach ($file->tracks as $track)
{
    // Statistics for whole track
    $track->stats->toArray();

    foreach ($track->segments as $segment) {
        // Statistics for segment of track
        $segment->stats->toArray();
    }
}

Distance calculator - add altitude in formulas

Hello, right now distance calculator does not add altitude difference between points to distance, and when it's calculating route with elevation gain or loss the results are slightly not correct.

I used pythagorean to include altitude to distance. I don't know if this is correct, but results looks more or less correct. :)

  public function distanceLatLngAlt(float $lat1, float $lng1, float $alt1, float $lat2, float $lng2, float $alt2)
    {
        $distance = $this->distanceLatLng($lat1, $lng1, $lat2, $lng2);

        $elevDiff = abs($alt1 - $alt2);

        return sqrt(pow($distance, 2) + pow($elevDiff, 2));
    }

This formula is tested against 141 km path. The difference between distance with 2 formulas is almost 1km.

What do you think if we integrate this or some other formulas to include altitude in distance calculations?

Route point <rtep> versus <rtept>

I'm using Garmin Basecamp 4.6.2 and the route points are identified as <rtept> and not <rtep>
I made changes to the code and now export and import work with BaseCamp. Can someone explain this to me? Which format is correct?
EDIT: to clarify the "tone", I am new to GPX conversion and wondered how I could be the first one to report this on a seemingly basic feature, or whether Garmin was using non-standard syntax.

Track Stats not calculated when first segment contains no data

Problem description

  1. phpGPX v1.0-RC5
  2. PHP v7.1.9
  3. GAIA GPS v10.9.12 (iPhone app) to map my hikes. When I export the GPX file it creates a track with an empty first segment. (See example below).

Code snippet you use

    echo "Created by: ". $file->creator; // GaiaGPS
    foreach ($file->tracks as $track)
    {
        echo "<B>Track Distance: </B>".$track->stats->distance; // always 0
        echo "<BR/>";
        
        foreach ($track->segments as $segment)
        {
            echo "<B>Segment Distance: </B>".$segment->stats->distance; // seg[0] always null
            echo "<BR/>";

        }
    }

Expected behaviour

Track distance should sum up all distances.

Possible solution

I started modifying Track.php recalculateStats(). I'll make a pull req shortly ;)

Example GPX snippet

  <trk>
    <name>Issue five</name>
    <desc>My Hike</desc>
    <trkseg>
    </trkseg>
    <trkseg>
      <trkpt lat="45.710399" lon="-121.362430">
        <ele>74.8</ele>
        <time>2018-03-11T16:01:39Z</time>
      </trkpt>
      <trkpt lat="45.711856" lon="-121.405851">
        <ele>414.0</ele>
        <time>2018-03-11T19:15:05Z</time>
      </trkpt>
    </trkseg>
  </trk>

Create statistics from GPX extensions

I just discovered phpGPX and while i am only trying to read out my gpx files, i have quickly discovered that heart rate is no being read out...

gpxtpx:hr107</gpxtpx:hr>

i am not a coder myself and more like a user, so i'll leave that as suggestion for following releases.
other than that, i am really amazed how easily phpGPX can be integrated, while looking around the best way to calculate the total distance from GPX file, this has helped me tremendously.

Class Error (Fatal error: Uncaught Error: Class "phpGPX\phpGPX" not found in)

Problem Description:

Error:
Fatal error: Uncaught Error: Class "phpGPX\phpGPX" not found in "C://MYFILEPATH"

I use phpGPX version 1.1.3 & PHP version 8.0.14

I installed phpGPX with composer with the command:
composer require sibyx/phpgpx:1.1.3

My code:

<?php
use phpGPX\phpGPX;

$gpx = new phpGPX();
	
$file = $gpx->load('example.gpx');
	
foreach ($file->tracks as $track)
{
    // Statistics for whole track
    $track->stats->toArray();
    
    foreach ($track->segments as $segment)
    {
    	// Statistics for segment of track
    	$segment->stats->toArray();
    }
}
?>

Someone know this?

Kind Regards,
Stef

@Sibyx

Parse of GPX file failse if lastpointTime is not prestent

When you try to parse a GPX file with only a timestamp on the firstpoint there will be an error.

I fixed the issue in the file Models/Segment.php with a check for the var $lastPoint->time
I changed line 100 from:
if (isset($firstPoint->time) && $firstPoint->time instanceof \DateTime) {
TO
if (isset($firstPoint->time) && isset($lastPoint->time) && $firstPoint->time instanceof \DateTime) {

Error when $person->links is null

Problem description

  1. Library version or last commit you have 1c1b4076
  2. PHP version you use 8.0.0
  3. Detailed problem description phpGPX\Parsers\PersonParser.php:48;"Invalid argument supplied for foreach()"

If you think that problem is connected with your file content, please attach it to the issue.

Code snippet you use

			$gpx = new phpGPX();
			$gpx_file = $gpx->load($filein);
....
			$p = new Person();
			$p->name = "blabla";
			$gpx_file->metadata->author = $p;
.....
			$out = $gpx_file->toXML()->saveXML();

Expected behaviour

script continue even if $person->links is null

Possible solution

diff --git "a/src/phpGPX/Parsers/PersonParser.php" "b/src/phpGPX/Parsers/PersonParser.php"
index 8795bc8..227b864 100644
--- "a/src/phpGPX/Parsers/PersonParser.php"
+++ "b/src/phpGPX/Parsers/PersonParser.php"
@@ -45,9 +45,11 @@ abstract class PersonParser
 			$node->appendChild($child);
 		}
 
-		foreach ($person->links as $link) {
-			$child = LinkParser::toXML($link, $document);
-			$node->appendChild($child);
+		if(!is_null($person->links)){
+			foreach ($person->links as $link) {
+				$child = LinkParser::toXML($link, $document);
+				$node->appendChild($child);
+			}
 		}
 
 		return $node;

and may the !is_null() test must be done somewhere else

Something interesting or funny

#confinedshortreading https://craphound.com/overclocked/Cory_Doctorow_-_Overclocked_-_When_Sysadmins_Ruled_the_Earth.html

Checklist

Put x into brackets if true.

[X] PHP version I use
[X] Package version I use

Cumulative elevation loss

Thanks for this wonderful library! It definitely eases the parsing of GPX to obtain it's related data.

I have noticed that you include the cumulative elevation gain, however I'm unable to see or to obtain the cumulative elevation loss, which is not as important for many people but it still is a decisive factor for some hikers who have legs' pain while descending tracks.

startedAt and finishedAt values are not present if the first (or last) point is without timestamp

Problem description

Current behaviour of the library (as of 1.1.1) fills the Stats object wih timestamp value of the first and last point object. If there is no such datetime, these value are not inside the Stats object.

Problematic code:

$firstPoint = &$this->points[0];
$lastPoint = end($this->points);

$this->stats->startedAt = $firstPoint->time; // problematic if null
$this->stats->finishedAt = $lastPoint->time;  // problematic if null

Expected behaviour

  • startedAt suppose to have the first not-null $point->time value
  • finishedAt suppose to have the last not-null $point->time value

waypoints not loaded correctly - they are ignored

The following simple gpx file of 4 waypoints and nothing else does not load correctly.

<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.1" creator="phpGPX/1.0-RC1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
  <metadata>
    <desc>My pretty awesome GPX file, created using phpGPX library!</desc>
    <link href="https://sibyx.github.io/phpgpx">
      <text>phpGPX Docs</text>
    </link>
    <time>2017-03-07T19:24:13+00:00</time>
  </metadata>
  <wpt lat="54.932862108889" lon="9.8606242161401">
    <ele>0</ele>
    <time>2017-03-07T19:25:13+00:00</time>
  </wpt>
  <wpt lat="54.832932373209" lon="9.7609220868149">
    <ele>10</ele>
    <time>2017-03-07T19:26:13+00:00</time>
  </wpt>
  <wpt lat="54.733277435212" lon="9.6618781654375">
    <ele>42.42</ele>
    <time>2017-03-07T19:27:13+00:00</time>
  </wpt>
  <wpt lat="54.633423261679" lon="9.5624398496799">
    <ele>12</ele>
    <time>2017-03-07T19:28:13+00:00</time>
  </wpt>
</gpx>

The following simple script

$of = dirname(__FILE__)."/test.gpx";
$gpx = new \phpGPX\phpGPX();
$file = $gpx->load($of);

produces a $gpx object with an empty waypoint array.

Removal of Summarizable and toArray

As part of the new major release, I propose the removal of the Summarizable interface along with its toArray method. This decision stems from my belief that all models should instead implement the JsonSerializable interface, thereby returning a GeoJSON compatible result where feasible.

The usage of arrays in this context seems antiquated and unnecessarily complex, hence it doesn't align with the direction of our project. I anticipate that the removal of these features won't be a significant loss for the users. However, I welcome any thoughts and potential concerns about this proposed change.

Originally posted by @Sibyx in #67 (comment)

Split loading and parsing in separate methods

Hi,

I played around and really like your package. It would be a nice addition if loading and parsing of the gpx data would be split in different methods, so it can be parsed from database entries.

Regards
Timo

Implementing way point and creation time extensions

Problem description

I need to re-create a gpx file that uses way point and creation time extensions as shown below.

    <extensions>
      <gpxx:WaypointExtension>
        <gpxx:DisplayMode>SymbolAndName</gpxx:DisplayMode>
      </gpxx:WaypointExtension>
      <wptx1:WaypointExtension>
        <wptx1:DisplayMode>SymbolAndName</wptx1:DisplayMode>
      </wptx1:WaypointExtension>
      <ctx:CreationTimeExtension>
        <ctx:CreationTime>2016-03-30T23:26:28Z</ctx:CreationTime>
      </ctx:CreationTimeExtension>
    </extensions>

Possible solution

I'm wondering if these extensions have been worked on before and/or if I can implement them would a pull request be accepted?

Something interesting or funny

Why does the Norwegian navy have barcodes on the side of their ships?
So when they arrive back in port, they can Scandinavian!

Error when TrkSeg is empty

TrkSeg can be empty on GPX 1.1 and it causes a problem in your library in method \phpGPX\Models\Track::recalculateStats when I try calculate statistics.

I got a few files with empty on end of files when I using export option on Endomondo.

I wrote quick fix to check trkseg is not empty and use only segments that have points:

$firstSegment = null;

foreach ($this->segments as $segment) {
    if (!empty($segment->points)) {
        if (is_null($firstSegment)) {
            $firstSegment = $segment;
        }

        $lastSegment = $segment;
    }
}

if (!isset($firstSegment) || !isset($lastSegment)) {
    return;
}

$firstPoint = $firstSegment->points[0];
$lastPoint = end($lastSegment->points);

but maybe you will find more optimal solution.

Statistics - get Bounds of the GPX Routes

A useful new feature would be to be able to obtain the bounds of points in the GPX file.
So you would retrieve the min/max Longitude and Latitude.
I am looking at this package to process walking routes to get overall stats. The bounds would allow me to display all my routes on a single map. Each walk would have an icon showing stats and a link to display the actual walk.
I have only just found this project but it looks good.

Middlewares

The additional computational processes for statistical analysis can be managed through middleware that implement the library interface. These middleware will execute in a specified sequence, post GPX parsing, following the basic statistical computations (or the library may include some middleware for elementary stats by default). To better understand my concept, consider the code below. It is merely a rough draft, hence open to modifications.

$phpgpx = new \phpGPX();

$phpgpx->middlewares->add(new \phpGPX\Middlewares\GpxReductionSmoothingMiddleware(2, 5));
$phpgpx->middlewares->add(new \phpGPX\Middlewares\TrackPointExtensionStatsMiddleware());
$phpgpx->middlewares->add(new CustomMiddleware());

$file = $phpgpx->load('example.gpx');

Implementing such a layer should substantially simplify the extension or modification of the library's behavior. I aim to develop a preliminary model for this layer. This should enhance the library's configurability (I'm not particularly fond of the current use of constants for this purpose).

Originally posted by @Sibyx in #67 (comment)

More examples

I wrote only a few examples of the library usage, it's a good idea to write more of them. Few ideas:

  • How to create GPX file from scratch
  • Configuration values
  • How to use GPX extensions

Add version GPX

Problem description

  1. Library version or last commit you have
  2. PHP version you use
  3. Detailed problem description

If you think that problem is connected with your file content, please attach it to the issue.

Code snippet you use

class phpGPX

$gpx->version = isset($xml['version']) ? (string)$xml['version'] : null;

class GpxFile 

	/**
	 * Version about the file.
	 * The original GPX 1.1 attribute.
	 * @var Version|null
	 */
	public $version;
	
	$this->version = null;
	
	'version' => SerializationHelper::stringOrNull($this->version),

Elevation string float becomes null in getJSON() call

Hi,

I was testing phpGPX with points from a database that contained timestamp, latitude, longitude and elevation and noticed that the JSON output had "null" in the elevation property. This is because the elevation was a string.

Remarkably enough, this problem did not occur when exporting to XML.

  1. Package version: 1.0-RC5, also tested on dev-master
  2. PHP version: 7.4.1

Expected behaviour

Silently cast the value to a float or null.

Possible solution

SerializationHelper::floatOrNull() should use is_numeric() instead of is_float() || is_integer()

Alternate solution

You could also throw an exception if the value is neither a float nor null. Maybe a 'strict mode' could be offered for people who prefer to get an exception.

Waypoints at the root of the gpx tag

Problem description

  1. Library version or last commit you have: 1.2.1
  2. PHP version you use: 8.2.1
  3. Detailed problem description

I need to generate a GPX file with waypoints at the root of the gpx tag. If I were to create a PR for this and the extensions (#41) would you consider it?

Code snippet you use

<gpx ...

  <metadata>
 <link href="https://www.adventurecycling.org">
      <text>Copyright 2021 Adventure Cycling Association</text>
    </link>
    <time>2021-08-31T19:10:51Z</time>
    <bounds maxlat="46.896566022187471" maxlon="-111.09867101535201" minlat="44.65610601939261" minlon="-114.17844995856285" />

 </metadata>
 
<wpt lat="45.293238032609224" lon="-111.9429490249604">
    <ele>0</ele>
    <time>2020-07-17T20:15:01Z</time>
    <name>?B&amp;B-Bennett House Country Inn B&amp;B</name>
    <cmt>tel://406-843-5220, tel://877-843-5220, 115 E. Idaho St., Virginia City, MT</cmt>
    <desc>tel://406-843-5220, tel://877-843-5220, 115 E. Idaho St., Virginia City, MT</desc>
    <sym>Lodging</sym>
    <type>user</type>
    <extensions>
      <gpxx:WaypointExtension>
        <gpxx:DisplayMode>SymbolAndName</gpxx:DisplayMode>
      </gpxx:WaypointExtension>
      <wptx1:WaypointExtension>
        <wptx1:DisplayMode>SymbolAndName</wptx1:DisplayMode>
      </wptx1:WaypointExtension>
      <ctx:CreationTimeExtension>
        <ctx:CreationTime>2020-07-17T20:15:01Z</ctx:CreationTime>
      </ctx:CreationTimeExtension>
    </extensions>
  </wpt>

Possible solution

Allow points at the root of the GPX File

Something interesting or funny

Where do bad rainbows go?

  • Prism. It's a light sentence and gives them time to reflect.

Checklist

Put x into brackets if true.

[ ] PHP version I use
[ ] Package version I use

phpGPX\Parsers\ExtensionParser::toXML(): Argument #1 ($extensions) must be of type phpGPX\Models\Extensions

Problem description

  1. Library version or last commit you have: 1.2.1
  2. PHP version you use: 8.2
  3. Detailed problem description

Having the code similar to:

<?php declare(strict_types=1);

namespace App\Services\Gpx;

use phpGPX\Models\Extensions\TrackPointExtension;
use phpGPX\Models\GpxFile;
use phpGPX\Models\Metadata;
use phpGPX\Models\Point;
use phpGPX\Models\Segment;
use phpGPX\Models\Track;
use App\Domains\Position\Model\Position as PositionModel;
use App\Domains\Trip\Model\Trip as TripModel;

class Gpx
{
    /**
     * @var \phpGPX\Models\GpxFile
     */
    protected GpxFile $file;

    /**
     * @param \App\Domains\Trip\Model\Trip $trip
     *
     * @return self
     */
    public function __construct(protected TripModel $trip)
    {
    }

    /**
     * @return self
     */
    public function generate(): self
    {
        $this->file();
        $this->track();

        return $this;
    }

    /**
     * @return string
     */
    public function toXml(): string
    {
        return $this->file->toXML()->saveXML();
    }

    /**
     * @return self
     */
    protected function file(): self
    {
        $this->file = new GpxFile();
        $this->file->metadata = new Metadata();
        $this->file->metadata->time = $this->trip->start_at;

        return $this;
    }

    /**
     * @return self
     */
    protected function track(): self
    {
        $track = new Track();
        $track->name = $this->trip->name;

        $segment = new Segment();

        foreach ($this->trip->positions as $position) {
            $segment->points[] = $this->point($position);
        }

        $track->segments[] = $segment;
        $track->recalculateStats();

        $this->file->tracks[] = $track;

        return $this;
    }

    /**
     * @param \App\Domains\Position\Model\Position $position
     *
     * @return \phpGPX\Models\Point
     */
    protected function point(PositionModel $position): Point
    {
        $point = new Point(Point::TRACKPOINT);
        $point->latitude = $position->latitude;
        $point->longitude = $position->longitude;
        $point->time = $position->date_at;

        $extension = new TrackPointExtension();
        $extension->speed = $position->speed;
        $extension->course = $position->direction;

        $point->extensions = $extension;

        return $point;
    }
}

After adding the TrackPointExtension to a point, I get the error:

phpGPX\Parsers\ExtensionParser::toXML(): Argument #1 ($extensions) must be of type phpGPX\Models\Extensions, phpGPX\Models\Extensions\TrackPointExtension given, called in /var/www/vendor/sibyx/phpgpx/src/phpGPX/Parsers/PointParser.php on line 157

Possible solution

Shouldn't TrackPointExtension extend AbstractExtension and AbstractExtension extends Extensions?

abstract class AbstractExtension implements Summarizable
{

namespace phpGPX\Models\Extensions;

use phpGPX\Models\Summarizable;
use phpGPX\Models\Extensions as ExtensionsBase;

abstract class AbstractExtension extends ExtensionsBase
{

Checklist

Put x into brackets if true.

[x] PHP version I use
[x] Package version I use

Cumulative Elevation Gain Stat

Hi,

Is there a way to calculate the cumulative elevation gain as part of the stats? I believe this is a new feature which doesn't exist today.

Thanks,
Steve

Error installing with composer

composer require sibyx/phpgpx:@1.1.2

[UnexpectedValueException]
Could not parse version constraint @1.1.2: Invalid version string "@1.1.2"

image

Write unit tests

To improve reliability and stability of the library it's a good practice to write PHPUnit tests.

cumulativeElevationGain and cumulativeElevationLoss not correct when missing parts of track with gps problem?

Hello,

Very nice work for the code you do.
I just want to report you a problem I see.

Here my gpx point, like you can see, it seems like there is missing points somewhere.

All data seems pretty ok with your code, except the "cumulativeElevationGain" and "cumulativeElevationLoss".

You code give me in the "stats" result of the "track":
+distance: 17597.984230898
+averageSpeed: 0.87508623724007
+averagePace: 1142.7445175619
+minAltitude: 1060.03
+maxAltitude: 1931.62
+cumulativeElevationGain: 1577.43
+cumulativeElevationLoss: 1604.36
+startedAt: DateTime @1604220199 {#4201 ▶}
+finishedAt: DateTime @1604240309 {#11583 ▶}
+duration: 20110

With classic call:
$gpx = new phpGPX();
$fileData = $gpx::load($filePath);

But good data for elevation gain must be: 932m (on alltrails.com) or 958m (on wikiloc.com)

You can see it here => https://www.alltrails.com/fr/explore/recording/grand-paradis-to-col-de-coux-circular-019fa4f

I have same result ok like "alltrails" when uploading my gpx point here on an other website => https://fr.wikiloc.com

ps: I think they can detect mis
gpx_file.zip
sing parts but do not know where :D

  1. Library version or last commit you have : 1.1.3
  2. PHP version you use: 7.4

[PR advise] Add coordinates for remarqued statistic points

Hi @Sibyx,
Many Thx for this great package!
I'm working on a PR to add coordinates for remarked statistic points (start, end, minAlt, maxAlt) , to facilitates wpt generation of them.
Which output would you prefer? (example with minAltitude):

  1. Nice but breaking
Array (
    [minAltitude] => Array
        (
            [ele] => 1518
            [lat] => 45.6139274
            [lng] => 7.3420498
        ),
    ...
    )
  1. ...not breaking
Array (
    [minAltitude] => 1518
    [minAltitudeCoords] => Array
        (
            [lat] => 45.6139274
            [lng] => 7.3420498
        ),
    ...
    )
  1. all added coords in a single Statistics key
Array (
    [coords] => Array (
        [minAltitude] => Array (
                [lat] => 45.6139274
                [lng] => 7.3420498
            ),
        [maxAltitude] => Array (
                [lat] => 45.5916625
                [lng] => 7.278847
            )
        ),
	...
    )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.