KML.class.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. <?php
  2. /*
  3. * Copyright (c) Patrick Hayes
  4. * Copyright (c) 2010-2011, Arnaud Renevier
  5. *
  6. * This code is open-source and licenced under the Modified BSD License.
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * PHP Geometry/KML encoder/decoder
  12. *
  13. * Mainly inspired/adapted from OpenLayers( http://www.openlayers.org )
  14. * Openlayers/format/WKT.js
  15. *
  16. * @package sfMapFishPlugin
  17. * @subpackage GeoJSON
  18. * @author Camptocamp <info@camptocamp.com>
  19. */
  20. class KML extends GeoAdapter
  21. {
  22. private $namespace = FALSE;
  23. private $nss = ''; // Name-space string. eg 'georss:'
  24. /**
  25. * Read KML string into geometry objects
  26. *
  27. * @param string $kml A KML string
  28. *
  29. * @return Geometry|GeometryCollection
  30. */
  31. public function read($kml) {
  32. return $this->geomFromText($kml);
  33. }
  34. /**
  35. * Serialize geometries into a KML string.
  36. *
  37. * @param Geometry $geometry
  38. *
  39. * @return string The KML string representation of the input geometries
  40. */
  41. public function write(Geometry $geometry, $namespace = FALSE) {
  42. if ($namespace) {
  43. $this->namespace = $namespace;
  44. $this->nss = $namespace.':';
  45. }
  46. return $this->geometryToKML($geometry);
  47. }
  48. public function geomFromText($text) {
  49. // Change to lower-case and strip all CDATA
  50. $text = mb_strtolower($text, mb_detect_encoding($text));
  51. $text = preg_replace('/<!\[cdata\[(.*?)\]\]>/s','',$text);
  52. // Load into DOMDOcument
  53. $xmlobj = new DOMDocument();
  54. @$xmlobj->loadXML($text);
  55. if ($xmlobj === false) {
  56. throw new Exception("Invalid KML: ". $text);
  57. }
  58. $this->xmlobj = $xmlobj;
  59. try {
  60. $geom = $this->geomFromXML();
  61. } catch(InvalidText $e) {
  62. throw new Exception("Cannot Read Geometry From KML: ". $text);
  63. } catch(Exception $e) {
  64. throw $e;
  65. }
  66. return $geom;
  67. }
  68. protected function geomFromXML() {
  69. $geometries = array();
  70. $geom_types = geoPHP::geometryList();
  71. $placemark_elements = $this->xmlobj->getElementsByTagName('placemark');
  72. if ($placemark_elements->length) {
  73. foreach ($placemark_elements as $placemark) {
  74. foreach ($placemark->childNodes as $child) {
  75. // Node names are all the same, except for MultiGeometry, which maps to GeometryCollection
  76. $node_name = $child->nodeName == 'multigeometry' ? 'geometrycollection' : $child->nodeName;
  77. if (array_key_exists($node_name, $geom_types)) {
  78. $function = 'parse'.$geom_types[$node_name];
  79. $geometries[] = $this->$function($child);
  80. }
  81. }
  82. }
  83. }
  84. else {
  85. // The document does not have a placemark, try to create a valid geometry from the root element
  86. $node_name = $this->xmlobj->documentElement->nodeName == 'multigeometry' ? 'geometrycollection' : $this->xmlobj->documentElement->nodeName;
  87. if (array_key_exists($node_name, $geom_types)) {
  88. $function = 'parse'.$geom_types[$node_name];
  89. $geometries[] = $this->$function($this->xmlobj->documentElement);
  90. }
  91. }
  92. return geoPHP::geometryReduce($geometries);
  93. }
  94. protected function childElements($xml, $nodename = '') {
  95. $children = array();
  96. if ($xml->childNodes) {
  97. foreach ($xml->childNodes as $child) {
  98. if ($child->nodeName == $nodename) {
  99. $children[] = $child;
  100. }
  101. }
  102. }
  103. return $children;
  104. }
  105. protected function parsePoint($xml) {
  106. $coordinates = $this->_extractCoordinates($xml);
  107. return new Point($coordinates[0][0],$coordinates[0][1]);
  108. }
  109. protected function parseLineString($xml) {
  110. $coordinates = $this->_extractCoordinates($xml);
  111. $point_array = array();
  112. foreach ($coordinates as $set) {
  113. $point_array[] = new Point($set[0],$set[1]);
  114. }
  115. return new LineString($point_array);
  116. }
  117. protected function parsePolygon($xml) {
  118. $components = array();
  119. $outer_boundary_element_a = $this->childElements($xml, 'outerboundaryis');
  120. $outer_boundary_element = $outer_boundary_element_a[0];
  121. $outer_ring_element_a = $this->childElements($outer_boundary_element, 'linearring');
  122. $outer_ring_element = $outer_ring_element_a[0];
  123. $components[] = $this->parseLineString($outer_ring_element);
  124. if (count($components) != 1) {
  125. throw new Exception("Invalid KML");
  126. }
  127. $inner_boundary_element_a = $this->childElements($xml, 'innerboundaryis');
  128. if (count($inner_boundary_element_a)) {
  129. foreach ($inner_boundary_element_a as $inner_boundary_element) {
  130. foreach ($this->childElements($inner_boundary_element, 'linearring') as $inner_ring_element) {
  131. $components[] = $this->parseLineString($inner_ring_element);
  132. }
  133. }
  134. }
  135. return new Polygon($components);
  136. }
  137. protected function parseGeometryCollection($xml) {
  138. $components = array();
  139. $geom_types = geoPHP::geometryList();
  140. foreach ($xml->childNodes as $child) {
  141. $nodeName = ($child->nodeName == 'linearring') ? 'linestring' : $child->nodeName;
  142. if (array_key_exists($nodeName, $geom_types)) {
  143. $function = 'parse'.$geom_types[$nodeName];
  144. $components[] = $this->$function($child);
  145. }
  146. }
  147. return new GeometryCollection($components);
  148. }
  149. protected function _extractCoordinates($xml) {
  150. $coord_elements = $this->childElements($xml, 'coordinates');
  151. $coordinates = array();
  152. if (count($coord_elements)) {
  153. $coord_sets = explode(' ', $coord_elements[0]->nodeValue);
  154. foreach ($coord_sets as $set_string) {
  155. $set_string = trim($set_string);
  156. if ($set_string) {
  157. $set_array = explode(',',$set_string);
  158. if (count($set_array) >= 2) {
  159. $coordinates[] = $set_array;
  160. }
  161. }
  162. }
  163. }
  164. return $coordinates;
  165. }
  166. private function geometryToKML($geom) {
  167. $type = strtolower($geom->getGeomType());
  168. switch ($type) {
  169. case 'point':
  170. return $this->pointToKML($geom);
  171. break;
  172. case 'linestring':
  173. return $this->linestringToKML($geom);
  174. break;
  175. case 'polygon':
  176. return $this->polygonToKML($geom);
  177. break;
  178. case 'multipoint':
  179. case 'multilinestring':
  180. case 'multipolygon':
  181. case 'geometrycollection':
  182. return $this->collectionToKML($geom);
  183. break;
  184. }
  185. }
  186. private function pointToKML($geom) {
  187. return '<'.$this->nss.'Point><'.$this->nss.'coordinates>'.$geom->getX().",".$geom->getY().'</'.$this->nss.'coordinates></'.$this->nss.'Point>';
  188. }
  189. private function linestringToKML($geom, $type = FALSE) {
  190. if (!$type) {
  191. $type = $geom->getGeomType();
  192. }
  193. $str = '<'.$this->nss . $type .'>';
  194. if (!$geom->isEmpty()) {
  195. $str .= '<'.$this->nss.'coordinates>';
  196. $i=0;
  197. foreach ($geom->getComponents() as $comp) {
  198. if ($i != 0) $str .= ' ';
  199. $str .= $comp->getX() .','. $comp->getY();
  200. $i++;
  201. }
  202. $str .= '</'.$this->nss.'coordinates>';
  203. }
  204. $str .= '</'. $this->nss . $type .'>';
  205. return $str;
  206. }
  207. public function polygonToKML($geom) {
  208. $components = $geom->getComponents();
  209. if (!empty($components)) {
  210. $str = '<'.$this->nss.'outerBoundaryIs>' . $this->linestringToKML($components[0], 'LinearRing') . '</'.$this->nss.'outerBoundaryIs>';
  211. foreach (array_slice($components, 1) as $comp) {
  212. $str .= '<'.$this->nss.'innerBoundaryIs>' . $this->linestringToKML($comp) . '</'.$this->nss.'innerBoundaryIs>';
  213. }
  214. }
  215. return '<'.$this->nss.'Polygon>'. $str .'</'.$this->nss.'Polygon>';
  216. }
  217. public function collectionToKML($geom) {
  218. $components = $geom->getComponents();
  219. $str = '<'.$this->nss.'MultiGeometry>';
  220. foreach ($geom->getComponents() as $comp) {
  221. $sub_adapter = new KML();
  222. $str .= $sub_adapter->write($comp);
  223. }
  224. return $str .'</'.$this->nss.'MultiGeometry>';
  225. }
  226. }