Files
spot/inc/converter.php

220 lines
6.6 KiB
PHP

<?php
/**
* GPX to GeoJSON Converter
*
* 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>' WHERE id_project = <id_project>;
* 3. Load any page
*
* To force gpx rebuild:
* ?a=build_geojson&name=<gpx_file_name>
*/
class Converter extends PhpObject {
public function __construct() {
parent::__construct(__CLASS__, Settings::DEBUG);
}
public static function convertToGeoJson($sFileName) {
$sFileName = basename($sFileName, Gpx::EXT);
$oGpx = new Gpx($sFileName);
$oGeoJson = new GeoJson($sFileName);
$oGeoJson->buildTracks($oGpx->getTracks());
if($oGeoJson->isSimplicationRequired()) $oGeoJson->buildTracks($oGpx->getTracks(), true);
$oGeoJson->saveFile();
return $oGpx->getLog().'<br />'.$oGeoJson->getLog();
}
public static function isGeoJsonValid($sFileName) {
$bResult = false;
$sGeoJsonFilePath = Geo::getFilePath($sFileName, GeoJson::EXT);
if(file_exists($sGeoJsonFilePath) && filemtime($sGeoJsonFilePath) > filemtime(Geo::getFilePath($sFileName, Gpx::EXT))) $bResult = true;
return $bResult;
}
}
class Geo extends PhpObject {
const GEO_FOLDER = 'geo/';
protected $asTracks;
protected $sFilePath;
public function __construct($sFileName) {
parent::__construct(get_class($this), Settings::DEBUG, PhpObject::MODE_HTML);
$this->sFilePath = self::getFilePath($sFileName, static::EXT);
$this->asTracks = array();
}
public static function getFilePath($sFileName, $sExt) {
return self::GEO_FOLDER.$sFileName.$sExt;
}
public function getLog() {
return $this->getCleanMessageStack(PhpObject::NOTICE_TAB);
}
}
class Gpx extends Geo {
const EXT = '.gpx';
public function __construct($sFileName) {
parent::__construct($sFileName);
$this->parseFile();
}
public function getTracks() {
return $this->asTracks;
}
private function parseFile() {
$this->addNotice('Parsing: '.$this->sFilePath);
$oXml = simplexml_load_file($this->sFilePath);
//Tracks
$this->addNotice('Converting '.count($oXml->trk).' tracks');
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;
}
//Waypoints
$this->addNotice('Ignoring '.count($oXml->wpt).' waypoints');
}
}
class GeoJson extends Geo {
const EXT = '.geojson';
const MAX_FILESIZE = 2; //MB
const MAX_DEVIATION = 0.1; //10%
public function __construct($sFileName) {
parent::__construct($sFileName);
}
public function saveFile() {
$this->addNotice('Saving '.$this->sFilePath);
file_put_contents($this->sFilePath, $this->buildGeoJson());
}
public function isSimplicationRequired() {
//Size in bytes
$iFileSize = strlen($this->buildGeoJson());
//Convert to MB
$iFileSize = round($iFileSize / pow(1024, 2), 2);
//Compare with max allowed size
$bFileTooLarge = ($iFileSize > self::MAX_FILESIZE);
if($bFileTooLarge) $this->addNotice('Output file is too large ('.$iFileSize.'MB > '.self::MAX_FILESIZE.'MB)');
return $bFileTooLarge;
}
public function buildTracks($asTracks, $bSimplify=false) {
$this->addNotice('Creating '.($bSimplify?'Simplified ':'').'GeoJson Tracks');
$this->asTracks = array();
foreach($asTracks as $asTrackProps) {
//Color mapping
switch($asTrackProps['color']) {
case 'DarkBlue':
$sType = 'main';
break;
case 'Magenta':
if($bSimplify) {
$this->addNotice('Ignoring Track "'.$asTrackProps['name'].' (off-track)');
continue 2; //discard tracks
}
else {
$sType = 'off-track';
break;
}
case 'Red':
$sType = 'hitchhiking';
break;
default:
$this->addNotice('Ignoring Track "'.$asTrackProps['name'].' (unknown color "'.$asTrackProps['color'].'")');
continue 2; //discard tracks
}
$asTrack = array(
'type' => 'Feature',
'properties' => array(
'name' => $asTrackProps['name'],
'type' => $sType,
'description' => $asTrackProps['desc']
),
'geometry' => array(
'type' => 'LineString',
'coordinates' => array()
)
);
//Track points
$asTrackPoints = $asTrackProps['points'];
$iPointCount = count($asTrackPoints);
$iInvalidPointCount = 0;
foreach($asTrackPoints as $iIndex=>$asPoint) {
if($bSimplify && $iIndex > 0 && $iIndex < ($iPointCount - 1)) {
if(!$this->isPointValid($asTrackPoints[$iIndex - 1], $asPoint, $asTrackPoints[$iIndex + 1])) {
$iInvalidPointCount++;
continue;
}
}
$asTrack['geometry']['coordinates'][] = array_values($asPoint);
}
$this->asTracks[] = $asTrack;
if($iInvalidPointCount > 0) $this->addNotice('Removing '.$iInvalidPointCount.'/'.$iPointCount.' points ('.round($iInvalidPointCount / $iPointCount * 100, 1).'%) from '.$asTrackProps['name']);
}
}
private function isPointValid($asPointA, $asPointO, $asPointB) {
/* A----O Calculate angle AO^OB
\ If angle is within [Pi - 10%; Pi + 10%], O can be discarded
\ O is valid otherwise
B
-> -> -> ->
Law of Cosines: angle = arccos(OA.OB / ||OA||.||OB||)
*/
$fVectorOA = array('lon'=>($asPointA['lon'] - $asPointO['lon']), 'lat'=> ($asPointA['lat'] - $asPointO['lat']));
$fVectorOB = array('lon'=>($asPointB['lon'] - $asPointO['lon']), 'lat'=> ($asPointB['lat'] - $asPointO['lat']));
$fVectorOAxOB = $fVectorOA['lon'] * $fVectorOB['lon'] + $fVectorOA['lat'] * $fVectorOB['lat'];
$fLengthOA = sqrt(pow($asPointA['lon'] - $asPointO['lon'], 2) + pow($asPointA['lat'] - $asPointO['lat'], 2));
$fLengthOB = sqrt(pow($asPointO['lon'] - $asPointB['lon'], 2) + pow($asPointO['lat'] - $asPointB['lat'], 2));
$fAngleAOB = acos($fVectorOAxOB/($fLengthOA * $fLengthOB));
return ($fAngleAOB <= (1 - self::MAX_DEVIATION) * M_PI || $fAngleAOB >= (1 + self::MAX_DEVIATION) * M_PI);
}
private function buildGeoJson() {
return json_encode(array('features'=>$this->asTracks));
}
}