Files
spot/inc/converter.php
2019-03-06 22:27:32 +01:00

129 lines
3.2 KiB
PHP

<?php
/**
* To convert a gpx file:
* 1. Add file <file_name>.gpx to geo/ folder
* 2. Assign file to project: UPDATE projects SET geofile = '<file_name>.geojson'
*/
class Converter extends PhpObject {
const GPX_EXT = '.gpx';
const GEO_EXT = '.geojson';
public function __construct() {
parent::__construct(__CLASS__, Settings::DEBUG);
}
public function convertToGeoJson($sGeoFile) {
$sFileName = pathinfo($sGeoFile, 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('features'=>array());
foreach($this->asTracks as $asTrackProps) {
//Color mapping
switch($asTrackProps['color']) {
case 'LightGray': continue 2; //discard track
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' => 'LineString',
'coordinates' => array()
)
);
foreach($asTrackProps['points'] as $asPoint) {
$asTrack['geometry']['coordinates'][] = array_values($asPoint);
}
$asTracks['features'][] = $asTrack;
}
return $asTracks;
}
}