Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Created October 7, 2019 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/3997a04f4aacc3209d86d7499d7dbe29 to your computer and use it in GitHub Desktop.
Save mtvbrianking/3997a04f4aacc3209d86d7499d7dbe29 to your computer and use it in GitHub Desktop.
Parse Google Earth Route KML
<?php
class XMLElement extends \SimpleXMLElement
{
public function get($attr, $default = null)
{
if (empty($this->{$attr})) {
return $default;
}
return $this->{$attr};
}
}
class InvalidRouteException extends \Exception
{
public function __construct($message, $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
function getCoordinates(XMLElement $route): string
{
// $route->Document->Placemark->LineString->coordinates
if(!$document = $route->get('Document')) {
throw new InvalidRouteException("Missing route->Document.");
}
if(!$placemark = $document->get('Placemark')) {
throw new InvalidRouteException("Missing route->Document->Placemark.");
}
if(!$lineString = $placemark->get('LineString')) {
throw new InvalidRouteException("Missing route->Document->Placemark->LineString.");
}
if(!$coordinates = $lineString->get('coordinates')) {
throw new InvalidRouteException("Missing route->Document->Placemark->LineString->coordinates.");
}
return $coordinates;
}
$route_kml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"
xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>Mombasa-Mbale.kml</name>
<StyleMap id="dir_route">
<Pair>
<key>normal</key>
<styleUrl>#dir_route1</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#dir_route0</styleUrl>
</Pair>
</StyleMap>
<Style id="dir_route0">
<LineStyle>
<color>7fa00000</color>
<width>6</width>
</LineStyle>
</Style>
<Style id="dir_route1">
<LineStyle>
<color>7fa00000</color>
<width>6</width>
</LineStyle>
</Style>
<Placemark id="1.3.2">
<name>Mombasa-Mbale</name>
<styleUrl>#dir_route</styleUrl>
<LineString>
<coordinates>
39.6326861,-4.0406225,0 39.6326861,-4.0406225,0 39.6325268,-4.0402901,0 39.6324947,-4.0402233,0
39.6324592,-4.040204,0 39.6324346,-4.0401842,0 39.6324228,-4.0401734,0 39.6324031,-4.040149,0
</coordinates>
</LineString>
</Placemark>
</Document>
</kml>
XML;
$route = simplexml_load_string($route_kml, XMLElement::class);
$coordinates = getCoordinates($route);
// Clean up
$coordinates = preg_replace('/\s+/S', '|', trim($coordinates));
// toArray
$coordinates = explode('|', $coordinates);
print json_encode($coordinates);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment