Change file name to match class name

This commit is contained in:
2021-06-28 20:48:05 +02:00
parent fb882d34f7
commit 3622f70aa1

View File

@@ -1,321 +1,321 @@
<?php <?php
namespace Franzz\Spot; namespace Franzz\Spot;
use Franzz\Objects\PhpObject; use Franzz\Objects\PhpObject;
use Franzz\Objects\ToolBox; use Franzz\Objects\ToolBox;
use \Settings; use \Settings;
/** /**
* GPX to GeoJSON Converter * GPX to GeoJSON Converter
* *
* To convert a gpx file: * To convert a gpx file:
* 1. Add file <file_name>.gpx to geo/ folder * 1. Add file <file_name>.gpx to geo/ folder
* 2. Assign file to project: UPDATE projects SET codename = '<file_name>' WHERE id_project = <id_project>; * 2. Assign file to project: UPDATE projects SET codename = '<file_name>' WHERE id_project = <id_project>;
* 3. Load any page * 3. Load any page
* *
* To force gpx rebuild: * To force gpx rebuild:
* ?a=build_geojson&name=<file_name> * ?a=build_geojson&name=<file_name>
*/ */
class Converter extends PhpObject { class Converter extends PhpObject {
public function __construct() { public function __construct() {
parent::__construct(__CLASS__, Settings::DEBUG); parent::__construct(__CLASS__, Settings::DEBUG);
} }
public static function convertToGeoJson($sCodeName) { public static function convertToGeoJson($sCodeName) {
$oGpx = new Gpx($sCodeName); $oGpx = new Gpx($sCodeName);
$oGeoJson = new GeoJson($sCodeName); $oGeoJson = new GeoJson($sCodeName);
$oGeoJson->buildTracks($oGpx->getTracks()); $oGeoJson->buildTracks($oGpx->getTracks());
if($oGeoJson->isSimplicationRequired()) $oGeoJson->buildTracks($oGpx->getTracks(), true); if($oGeoJson->isSimplicationRequired()) $oGeoJson->buildTracks($oGpx->getTracks(), true);
$oGeoJson->sortOffTracks(); $oGeoJson->sortOffTracks();
$oGeoJson->saveFile(); $oGeoJson->saveFile();
return $oGpx->getLog().'<br />'.$oGeoJson->getLog(); return $oGpx->getLog().'<br />'.$oGeoJson->getLog();
} }
public static function isGeoJsonValid($sCodeName) { public static function isGeoJsonValid($sCodeName) {
$bResult = false; $bResult = false;
$sGeoJsonFilePath = Geo::getFilePath($sCodeName, GeoJson::EXT); $sGeoJsonFilePath = Geo::getFilePath($sCodeName, GeoJson::EXT);
if(file_exists($sGeoJsonFilePath) && filemtime($sGeoJsonFilePath) > filemtime(Geo::getFilePath($sCodeName, Gpx::EXT))) $bResult = true; if(file_exists($sGeoJsonFilePath) && filemtime($sGeoJsonFilePath) > filemtime(Geo::getFilePath($sCodeName, Gpx::EXT))) $bResult = true;
return $bResult; return $bResult;
} }
} }
class Geo extends PhpObject { class Geo extends PhpObject {
const GEO_FOLDER = 'geo/'; const GEO_FOLDER = 'geo/';
const OPT_SIMPLE = 'simplification'; const OPT_SIMPLE = 'simplification';
protected $asTracks; protected $asTracks;
protected $sFilePath; protected $sFilePath;
public function __construct($sCodeName) { public function __construct($sCodeName) {
parent::__construct(get_class($this), Settings::DEBUG, PhpObject::MODE_HTML); parent::__construct(get_class($this), Settings::DEBUG, PhpObject::MODE_HTML);
$this->sFilePath = self::getFilePath($sCodeName, static::EXT); $this->sFilePath = self::getFilePath($sCodeName, static::EXT);
$this->asTracks = array(); $this->asTracks = array();
} }
public static function getFilePath($sCodeName, $sExt) { public static function getFilePath($sCodeName, $sExt) {
return self::GEO_FOLDER.$sCodeName.$sExt; return self::GEO_FOLDER.$sCodeName.$sExt;
} }
public function getLog() { public function getLog() {
return $this->getCleanMessageStack(PhpObject::NOTICE_TAB); return $this->getCleanMessageStack(PhpObject::NOTICE_TAB);
} }
} }
class Gpx extends Geo { class Gpx extends Geo {
const EXT = '.gpx'; const EXT = '.gpx';
public function __construct($sCodeName) { public function __construct($sCodeName) {
parent::__construct($sCodeName); parent::__construct($sCodeName);
$this->parseFile(); $this->parseFile();
} }
public function getTracks() { public function getTracks() {
return $this->asTracks; return $this->asTracks;
} }
private function parseFile() { private function parseFile() {
$this->addNotice('Parsing: '.$this->sFilePath); $this->addNotice('Parsing: '.$this->sFilePath);
$oXml = simplexml_load_file($this->sFilePath); $oXml = simplexml_load_file($this->sFilePath);
//Tracks //Tracks
$this->addNotice('Converting '.count($oXml->trk).' tracks'); $this->addNotice('Converting '.count($oXml->trk).' tracks');
foreach($oXml->trk as $aoTrack) { foreach($oXml->trk as $aoTrack) {
$asTrack = array( $asTrack = array(
'name' => (string) $aoTrack->name, 'name' => (string) $aoTrack->name,
'desc' => str_replace("\n", '', ToolBox::fixEOL((strip_tags($aoTrack->desc)))), 'desc' => str_replace("\n", '', ToolBox::fixEOL((strip_tags($aoTrack->desc)))),
'cmt' => ToolBox::fixEOL((strip_tags($aoTrack->cmt))), 'cmt' => ToolBox::fixEOL((strip_tags($aoTrack->cmt))),
'color' => (string) $aoTrack->extensions->children('gpxx', true)->TrackExtension->DisplayColor, 'color' => (string) $aoTrack->extensions->children('gpxx', true)->TrackExtension->DisplayColor,
'points'=> array() 'points'=> array()
); );
foreach($aoTrack->trkseg as $asSegment) { foreach($aoTrack->trkseg as $asSegment) {
foreach($asSegment as $asPoint) { foreach($asSegment as $asPoint) {
$asTrack['points'][] = array( $asTrack['points'][] = array(
'lon' => (float) $asPoint['lon'], 'lon' => (float) $asPoint['lon'],
'lat' => (float) $asPoint['lat'], 'lat' => (float) $asPoint['lat'],
'ele' => (int) $asPoint->ele 'ele' => (int) $asPoint->ele
); );
} }
} }
$this->asTracks[] = $asTrack; $this->asTracks[] = $asTrack;
} }
//Waypoints //Waypoints
$this->addNotice('Ignoring '.count($oXml->wpt).' waypoints'); $this->addNotice('Ignoring '.count($oXml->wpt).' waypoints');
} }
} }
class GeoJson extends Geo { class GeoJson extends Geo {
const EXT = '.geojson'; const EXT = '.geojson';
const MAX_FILESIZE = 2; //MB const MAX_FILESIZE = 2; //MB
const MAX_DEVIATION_FLAT = 0.1; //10% const MAX_DEVIATION_FLAT = 0.1; //10%
const MAX_DEVIATION_ELEV = 0.1; //10% const MAX_DEVIATION_ELEV = 0.1; //10%
public function __construct($sCodeName) { public function __construct($sCodeName) {
parent::__construct($sCodeName); parent::__construct($sCodeName);
} }
public function saveFile() { public function saveFile() {
$this->addNotice('Saving '.$this->sFilePath); $this->addNotice('Saving '.$this->sFilePath);
file_put_contents($this->sFilePath, $this->buildGeoJson()); file_put_contents($this->sFilePath, $this->buildGeoJson());
} }
public function isSimplicationRequired() { public function isSimplicationRequired() {
//Size in bytes //Size in bytes
$iFileSize = strlen($this->buildGeoJson()); $iFileSize = strlen($this->buildGeoJson());
//Convert to MB //Convert to MB
$iFileSize = round($iFileSize / pow(1024, 2), 2); $iFileSize = round($iFileSize / pow(1024, 2), 2);
//Compare with max allowed size //Compare with max allowed size
$bFileTooLarge = ($iFileSize > self::MAX_FILESIZE); $bFileTooLarge = ($iFileSize > self::MAX_FILESIZE);
if($bFileTooLarge) $this->addNotice('Output file is too large ('.$iFileSize.'MB > '.self::MAX_FILESIZE.'MB)'); if($bFileTooLarge) $this->addNotice('Output file is too large ('.$iFileSize.'MB > '.self::MAX_FILESIZE.'MB)');
return $bFileTooLarge; return $bFileTooLarge;
} }
public function buildTracks($asTracks, $bSimplify=false) { public function buildTracks($asTracks, $bSimplify=false) {
$this->addNotice('Creating '.($bSimplify?'Simplified ':'').'GeoJson Tracks'); $this->addNotice('Creating '.($bSimplify?'Simplified ':'').'GeoJson Tracks');
$iGlobalInvalidPointCount = 0; $iGlobalInvalidPointCount = 0;
$iGlobalPointCount = 0; $iGlobalPointCount = 0;
$this->asTracks = array(); $this->asTracks = array();
foreach($asTracks as $asTrackProps) { foreach($asTracks as $asTrackProps) {
$asOptions = $this->parseOptions($asTrackProps['cmt']); $asOptions = $this->parseOptions($asTrackProps['cmt']);
//Color mapping //Color mapping
switch($asTrackProps['color']) { switch($asTrackProps['color']) {
case 'DarkBlue': case 'DarkBlue':
$sType = 'main'; $sType = 'main';
break; break;
case 'Magenta': case 'Magenta':
if($bSimplify && $asOptions[self::OPT_SIMPLE]!='keep') { if($bSimplify && $asOptions[self::OPT_SIMPLE]!='keep') {
$this->addNotice('Ignoring Track "'.$asTrackProps['name'].' (off-track)'); $this->addNotice('Ignoring Track "'.$asTrackProps['name'].' (off-track)');
continue 2; //discard tracks continue 2; //discard tracks
} }
else { else {
$sType = 'off-track'; $sType = 'off-track';
break; break;
} }
case 'Red': case 'Red':
$sType = 'hitchhiking'; $sType = 'hitchhiking';
break; break;
default: default:
$this->addNotice('Ignoring Track "'.$asTrackProps['name'].' (unknown color "'.$asTrackProps['color'].'")'); $this->addNotice('Ignoring Track "'.$asTrackProps['name'].' (unknown color "'.$asTrackProps['color'].'")');
continue 2; //discard tracks continue 2; //discard tracks
} }
$asTrack = array( $asTrack = array(
'type' => 'Feature', 'type' => 'Feature',
'properties' => array( 'properties' => array(
'name' => $asTrackProps['name'], 'name' => $asTrackProps['name'],
'type' => $sType, 'type' => $sType,
'description' => $asTrackProps['desc'] 'description' => $asTrackProps['desc']
), ),
'geometry' => array( 'geometry' => array(
'type' => 'LineString', 'type' => 'LineString',
'coordinates' => array() 'coordinates' => array()
) )
); );
//Track points //Track points
$asTrackPoints = $asTrackProps['points']; $asTrackPoints = $asTrackProps['points'];
$iPointCount = count($asTrackPoints); $iPointCount = count($asTrackPoints);
$iInvalidPointCount = 0; $iInvalidPointCount = 0;
$asPrevPoint = array(); $asPrevPoint = array();
foreach($asTrackPoints as $iIndex=>$asPoint) { foreach($asTrackPoints as $iIndex=>$asPoint) {
$asNextPoint = ($iIndex < ($iPointCount - 1))?$asTrackPoints[$iIndex + 1]:array(); $asNextPoint = ($iIndex < ($iPointCount - 1))?$asTrackPoints[$iIndex + 1]:array();
if($bSimplify && !empty($asPrevPoint) && !empty($asNextPoint)) { if($bSimplify && !empty($asPrevPoint) && !empty($asNextPoint)) {
if(!$this->isPointValid($asPrevPoint, $asPoint, $asNextPoint)) { if(!$this->isPointValid($asPrevPoint, $asPoint, $asNextPoint)) {
$iInvalidPointCount++; $iInvalidPointCount++;
continue; continue;
} }
} }
$asTrack['geometry']['coordinates'][] = array_values($asPoint); $asTrack['geometry']['coordinates'][] = array_values($asPoint);
$asPrevPoint = $asPoint; $asPrevPoint = $asPoint;
} }
$this->asTracks[] = $asTrack; $this->asTracks[] = $asTrack;
$iGlobalInvalidPointCount += $iInvalidPointCount; $iGlobalInvalidPointCount += $iInvalidPointCount;
$iGlobalPointCount += $iPointCount; $iGlobalPointCount += $iPointCount;
if($iInvalidPointCount > 0) $this->addNotice('Removing '.$iInvalidPointCount.'/'.$iPointCount.' points ('.round($iInvalidPointCount / $iPointCount * 100, 1).'%) from '.$asTrackProps['name']); if($iInvalidPointCount > 0) $this->addNotice('Removing '.$iInvalidPointCount.'/'.$iPointCount.' points ('.round($iInvalidPointCount / $iPointCount * 100, 1).'%) from '.$asTrackProps['name']);
} }
if($bSimplify) $this->addNotice('Total: '.$iGlobalInvalidPointCount.'/'.$iGlobalPointCount.' points removed ('.round($iGlobalInvalidPointCount / $iGlobalPointCount * 100, 1).'%)'); if($bSimplify) $this->addNotice('Total: '.$iGlobalInvalidPointCount.'/'.$iGlobalPointCount.' points removed ('.round($iGlobalInvalidPointCount / $iGlobalPointCount * 100, 1).'%)');
} }
public function sortOffTracks() { public function sortOffTracks() {
$this->addNotice('Sorting off-tracks'); $this->addNotice('Sorting off-tracks');
//Find first & last track points //Find first & last track points
$asTracksEnds = array(); $asTracksEnds = array();
$asTracks = array(); $asTracks = array();
foreach($this->asTracks as $iTrackId=>$asTrack) { foreach($this->asTracks as $iTrackId=>$asTrack) {
$sTrackId = 't'.$iTrackId; $sTrackId = 't'.$iTrackId;
$asTracksEnds[$sTrackId] = array('first'=>reset($asTrack['geometry']['coordinates']), 'last'=>end($asTrack['geometry']['coordinates'])); $asTracksEnds[$sTrackId] = array('first'=>reset($asTrack['geometry']['coordinates']), 'last'=>end($asTrack['geometry']['coordinates']));
$asTracks[$sTrackId] = $asTrack; $asTracks[$sTrackId] = $asTrack;
} }
//Find variants close-by tracks //Find variants close-by tracks
$asClonedTracks = $asTracks; $asClonedTracks = $asTracks;
foreach($asClonedTracks as $sTrackId=>$asTrack) { foreach($asClonedTracks as $sTrackId=>$asTrack) {
if($asTrack['properties']['type'] != 'off-track') continue; if($asTrack['properties']['type'] != 'off-track') continue;
$iMinDistance = INF; $iMinDistance = INF;
$sConnectedTrackId = 0; $sConnectedTrackId = 0;
$iPosition = 0; $iPosition = 0;
//Test all track ending points to find the closest //Test all track ending points to find the closest
foreach($asTracksEnds as $sTrackEndId=>$asTrackEnds) { foreach($asTracksEnds as $sTrackEndId=>$asTrackEnds) {
if($sTrackEndId != $sTrackId) { if($sTrackEndId != $sTrackId) {
//Calculate distance between the last point of the track and every starting point of other tracks //Calculate distance between the last point of the track and every starting point of other tracks
$iDistance = self::getDistance($asTracksEnds[$sTrackId]['last'], $asTrackEnds['first']); $iDistance = self::getDistance($asTracksEnds[$sTrackId]['last'], $asTrackEnds['first']);
if($iDistance < $iMinDistance) { if($iDistance < $iMinDistance) {
$sConnectedTrackId = $sTrackEndId; $sConnectedTrackId = $sTrackEndId;
$iPosition = 0; //Track before the Connected Track $iPosition = 0; //Track before the Connected Track
$iMinDistance = $iDistance; $iMinDistance = $iDistance;
} }
//Calculate distance between the first point of the track and every ending point of other tracks //Calculate distance between the first point of the track and every ending point of other tracks
$iDistance = self::getDistance($asTracksEnds[$sTrackId]['first'], $asTrackEnds['last']); $iDistance = self::getDistance($asTracksEnds[$sTrackId]['first'], $asTrackEnds['last']);
if($iDistance < $iMinDistance) { if($iDistance < $iMinDistance) {
$sConnectedTrackId = $sTrackEndId; $sConnectedTrackId = $sTrackEndId;
$iPosition = +1; //Track after the Connected Track $iPosition = +1; //Track after the Connected Track
$iMinDistance = $iDistance; $iMinDistance = $iDistance;
} }
} }
} }
//Move track //Move track
unset($asTracks[$sTrackId]); unset($asTracks[$sTrackId]);
$iOffset = array_search($sConnectedTrackId, array_keys($asTracks)) + $iPosition; $iOffset = array_search($sConnectedTrackId, array_keys($asTracks)) + $iPosition;
$asTracks = array_slice($asTracks, 0, $iOffset) + array($sTrackId => $asTrack) + array_slice($asTracks, $iOffset); $asTracks = array_slice($asTracks, 0, $iOffset) + array($sTrackId => $asTrack) + array_slice($asTracks, $iOffset);
} }
$this->asTracks = array_values($asTracks); $this->asTracks = array_values($asTracks);
} }
private function parseOptions($sComment){ private function parseOptions($sComment){
$asOptions = array(self::OPT_SIMPLE=>''); $asOptions = array(self::OPT_SIMPLE=>'');
foreach(explode("\n", $sComment) as $sLine) { foreach(explode("\n", $sComment) as $sLine) {
$asOptions[mb_strtolower(trim(mb_strstr($sLine, ':', true)))] = mb_strtolower(trim(mb_substr(mb_strstr($sLine, ':'), 1))); $asOptions[mb_strtolower(trim(mb_strstr($sLine, ':', true)))] = mb_strtolower(trim(mb_substr(mb_strstr($sLine, ':'), 1)));
} }
return $asOptions; return $asOptions;
} }
private function isPointValid($asPointA, $asPointO, $asPointB) { private function isPointValid($asPointA, $asPointO, $asPointB) {
/* A----O Calculate angle AO^OB /* A----O Calculate angle AO^OB
* \ If angle is within [90% Pi ; 110% Pi], O can be discarded * \ If angle is within [90% Pi ; 110% Pi], O can be discarded
* \ O is valid otherwise * \ O is valid otherwise
* B * B
*/ */
//Path Turn Check -> -> -> -> //Path Turn Check -> -> -> ->
//Law of Cosines (vector): angle = arccos(OA.OB / ||OA||.||OB||) //Law of Cosines (vector): angle = arccos(OA.OB / ||OA||.||OB||)
$fVectorOA = array('lon'=>($asPointA['lon'] - $asPointO['lon']), 'lat'=> ($asPointA['lat'] - $asPointO['lat'])); $fVectorOA = array('lon'=>($asPointA['lon'] - $asPointO['lon']), 'lat'=> ($asPointA['lat'] - $asPointO['lat']));
$fVectorOB = array('lon'=>($asPointB['lon'] - $asPointO['lon']), 'lat'=> ($asPointB['lat'] - $asPointO['lat'])); $fVectorOB = array('lon'=>($asPointB['lon'] - $asPointO['lon']), 'lat'=> ($asPointB['lat'] - $asPointO['lat']));
$fLengthOA = sqrt(pow($asPointA['lon'] - $asPointO['lon'], 2) + pow($asPointA['lat'] - $asPointO['lat'], 2)); $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)); $fLengthOB = sqrt(pow($asPointO['lon'] - $asPointB['lon'], 2) + pow($asPointO['lat'] - $asPointB['lat'], 2));
$fVectorOAxOB = $fVectorOA['lon'] * $fVectorOB['lon'] + $fVectorOA['lat'] * $fVectorOB['lat']; $fVectorOAxOB = $fVectorOA['lon'] * $fVectorOB['lon'] + $fVectorOA['lat'] * $fVectorOB['lat'];
$fAngleAOB = acos($fVectorOAxOB/($fLengthOA * $fLengthOB)); $fAngleAOB = acos($fVectorOAxOB/($fLengthOA * $fLengthOB));
//Elevation Check //Elevation Check
//Law of Cosines: angle = arccos((OB² + AO² - AB²) / (2*OB*AO)) //Law of Cosines: angle = arccos((OB² + AO² - AB²) / (2*OB*AO))
$fLengthAB = sqrt(pow($asPointB['ele'] - $asPointA['ele'], 2) + pow($fLengthOA + $fLengthOB, 2)); $fLengthAB = sqrt(pow($asPointB['ele'] - $asPointA['ele'], 2) + pow($fLengthOA + $fLengthOB, 2));
$fLengthAO = sqrt(pow($asPointO['ele'] - $asPointA['ele'], 2) + pow($fLengthOA, 2)); $fLengthAO = sqrt(pow($asPointO['ele'] - $asPointA['ele'], 2) + pow($fLengthOA, 2));
$fLengthOB = sqrt(pow($asPointB['ele'] - $asPointO['ele'], 2) + pow($fLengthOB, 2)); $fLengthOB = sqrt(pow($asPointB['ele'] - $asPointO['ele'], 2) + pow($fLengthOB, 2));
$fAngleAOBElev = acos((pow($fLengthOB, 2) + pow($fLengthAO, 2) - pow($fLengthAB, 2)) / (2 * $fLengthOB * $fLengthAO)); $fAngleAOBElev = acos((pow($fLengthOB, 2) + pow($fLengthAO, 2) - pow($fLengthAB, 2)) / (2 * $fLengthOB * $fLengthAO));
return ($fAngleAOB <= (1 - self::MAX_DEVIATION_FLAT) * M_PI || $fAngleAOB >= (1 + self::MAX_DEVIATION_FLAT) * M_PI || return ($fAngleAOB <= (1 - self::MAX_DEVIATION_FLAT) * M_PI || $fAngleAOB >= (1 + self::MAX_DEVIATION_FLAT) * M_PI ||
$fAngleAOBElev <= (1 - self::MAX_DEVIATION_ELEV) * M_PI || $fAngleAOBElev >= (1 + self::MAX_DEVIATION_ELEV) * M_PI); $fAngleAOBElev <= (1 - self::MAX_DEVIATION_ELEV) * M_PI || $fAngleAOBElev >= (1 + self::MAX_DEVIATION_ELEV) * M_PI);
} }
private function buildGeoJson() { private function buildGeoJson() {
return json_encode(array('type'=>'FeatureCollection', 'features'=>$this->asTracks)); return json_encode(array('type'=>'FeatureCollection', 'features'=>$this->asTracks));
} }
private static function getDistance($asPointA, $asPointB) { private static function getDistance($asPointA, $asPointB) {
$fLatFrom = $asPointA[1]; $fLatFrom = $asPointA[1];
$fLonFrom = $asPointA[0]; $fLonFrom = $asPointA[0];
$fLatTo = $asPointB[1]; $fLatTo = $asPointB[1];
$fLonTo = $asPointB[0]; $fLonTo = $asPointB[0];
$fRad = M_PI / 180; $fRad = M_PI / 180;
//Calculate distance from latitude and longitude //Calculate distance from latitude and longitude
$fTheta = $fLonFrom - $fLonTo; $fTheta = $fLonFrom - $fLonTo;
$fDistance = sin($fLatFrom * $fRad) * sin($fLatTo * $fRad) + cos($fLatFrom * $fRad) * cos($fLatTo * $fRad) * cos($fTheta * $fRad); $fDistance = sin($fLatFrom * $fRad) * sin($fLatTo * $fRad) + cos($fLatFrom * $fRad) * cos($fLatTo * $fRad) * cos($fTheta * $fRad);
return acos($fDistance) / $fRad * 60 * 1.853; return acos($fDistance) / $fRad * 60 * 1.853;
} }
} }