GPX to GeoJson converter

This commit is contained in:
2019-02-12 20:00:59 +01:00
parent b49445a85e
commit 50878503e5
9 changed files with 236739 additions and 189 deletions

130
inc/converter.php Normal file
View File

@@ -0,0 +1,130 @@
<?php
class Converter extends PhpObject {
const GPX_EXT = '.gpx';
const GEO_EXT = '.geojson';
/**
* Project to convert
* @var Project
*/
private $oProject;
public function __construct(&$oProject) {
parent::__construct(__CLASS__, Settings::DEBUG);
$this->oProject = &$oProject;
}
public function convertToGeoJson() {
$sFileName = pathinfo($this->oProject->getGeoFile(), PATHINFO_FILENAME);
$sGpxFileName = $sFileName.self::GPX_EXT;
$sGeoJsonFileName = $sFileName.self::GEO_EXT;
$oGpx = new Gpx($sGpxFileName);
$oGeoJson = new GeoJson($sGeoJsonFileName);
$oGeoJson->setTracks($oGpx->getTracks());
$oGeoJson->saveFile();
}
}
class Geo extends PhpObject {
const GEO_FOLDER = 'geo/';
protected $asTracks;
protected $sFilePath;
public function __construct($sFileName) {
parent::__construct(__CLASS__, Settings::DEBUG);
$this->sFilePath = self::GEO_FOLDER.$sFileName;
$this->asTracks = array();
}
}
class Gpx extends Geo {
public function __construct($sFileName) {
parent::__construct($sFileName);
$this->parseFile();
}
public function getTracks() {
return $this->asTracks;
}
private function parseFile() {
$oXml = simplexml_load_file($this->sFilePath);
foreach($oXml->trk as $aoTrack) {
$asTrack = array(
'name' => (string) $aoTrack->name,
'desc' => str_replace("\n", '', ToolBox::fixEOL((strip_tags($aoTrack->desc)))),
'color' => (string) $aoTrack->extensions->children('gpxx', true)->TrackExtension->DisplayColor,
'points'=> array()
);
foreach($aoTrack->trkseg as $asSegment) {
foreach($asSegment as $asPoint) {
$asTrack['points'][] = array(
'lon' => (float) $asPoint['lon'],
'lat' => (float) $asPoint['lat'],
//'ele' => (int) $asPoint->ele
);
}
}
$this->asTracks[] = $asTrack;
}
}
}
class GeoJson extends Geo {
public function __construct($sFileName) {
parent::__construct($sFileName);
}
public function setTracks($asTracks) {
$this->asTracks = $asTracks;
}
public function saveFile() {
$sContent = json_encode($this->getGeoJson());
//$sContent = str_replace('{"type":"Feature"', "\n\t{\"type\":\"Feature\"", $sContent);
file_put_contents($this->sFilePath, $sContent);
}
private function getGeoJson() {
$asTracks = array();
foreach($this->asTracks as $asTrackProps) {
switch($asTrackProps['color']) {
case 'LightGray': continue 2;
case 'Magenta': $sType = 'off-track'; break;
case 'Red': $sType = 'hitchhiking'; break;
default: $sType = 'main'; break;
}
$asTrack = array(
'type' => 'Feature',
'properties' => array(
'name' => $asTrackProps['name'],
'type' => $sType,
'description' => $asTrackProps['desc']
),
'geometry' => array(
'type' => 'MultiLineString',
'coordinates' => array()
)
);
foreach($asTrackProps['points'] as $asPoint) {
$asTrack['geometry']['coordinates'][0][] = array_values($asPoint);
}
$asTracks[] = $asTrack;
}
return $asTracks;
}
}