KML.class.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. if (!empty($coordinates)) {
  108. return new Point($coordinates[0][0],$coordinates[0][1]);
  109. }
  110. else {
  111. return new Point();
  112. }
  113. }
  114. protected function parseLineString($xml) {
  115. $coordinates = $this->_extractCoordinates($xml);
  116. $point_array = array();
  117. foreach ($coordinates as $set) {
  118. $point_array[] = new Point($set[0],$set[1]);
  119. }
  120. return new LineString($point_array);
  121. }
  122. protected function parsePolygon($xml) {
  123. $components = array();
  124. $outer_boundary_element_a = $this->childElements($xml, 'outerboundaryis');
  125. if (empty($outer_boundary_element_a)) {
  126. return new Polygon(); // It's an empty polygon
  127. }
  128. $outer_boundary_element = $outer_boundary_element_a[0];
  129. $outer_ring_element_a = $this->childElements($outer_boundary_element, 'linearring');
  130. $outer_ring_element = $outer_ring_element_a[0];
  131. $components[] = $this->parseLineString($outer_ring_element);
  132. if (count($components) != 1) {
  133. throw new Exception("Invalid KML");
  134. }
  135. $inner_boundary_element_a = $this->childElements($xml, 'innerboundaryis');
  136. if (count($inner_boundary_element_a)) {
  137. foreach ($inner_boundary_element_a as $inner_boundary_element) {
  138. foreach ($this->childElements($inner_boundary_element, 'linearring') as $inner_ring_element) {
  139. $components[] = $this->parseLineString($inner_ring_element);
  140. }
  141. }
  142. }
  143. return new Polygon($components);
  144. }
  145. protected function parseGeometryCollection($xml) {
  146. $components = array();
  147. $geom_types = geoPHP::geometryList();
  148. foreach ($xml->childNodes as $child) {
  149. $nodeName = ($child->nodeName == 'linearring') ? 'linestring' : $child->nodeName;
  150. if (array_key_exists($nodeName, $geom_types)) {
  151. $function = 'parse'.$geom_types[$nodeName];
  152. $components[] = $this->$function($child);
  153. }
  154. }
  155. return new GeometryCollection($components);
  156. }
  157. protected function _extractCoordinates($xml) {
  158. $coord_elements = $this->childElements($xml, 'coordinates');
  159. $coordinates = array();
  160. if (count($coord_elements)) {
  161. $coord_sets = explode(' ', preg_replace('/[\r\n]+/', ' ', $coord_elements[0]->nodeValue));
  162. foreach ($coord_sets as $set_string) {
  163. $set_string = trim($set_string);
  164. if ($set_string) {
  165. $set_array = explode(',',$set_string);
  166. if (count($set_array) >= 2) {
  167. $coordinates[] = $set_array;
  168. }
  169. }
  170. }
  171. }
  172. return $coordinates;
  173. }
  174. private function geometryToKML($geom) {
  175. $type = strtolower($geom->getGeomType());
  176. switch ($type) {
  177. case 'point':
  178. return $this->pointToKML($geom);
  179. break;
  180. case 'linestring':
  181. return $this->linestringToKML($geom);
  182. break;
  183. case 'polygon':
  184. return $this->polygonToKML($geom);
  185. break;
  186. case 'multipoint':
  187. case 'multilinestring':
  188. case 'multipolygon':
  189. case 'geometrycollection':
  190. return $this->collectionToKML($geom);
  191. break;
  192. }
  193. }
  194. private function pointToKML($geom) {
  195. $out = '<'.$this->nss.'Point>';
  196. if (!$geom->isEmpty()) {
  197. $out .= '<'.$this->nss.'coordinates>'.$geom->getX().",".$geom->getY().'</'.$this->nss.'coordinates>';
  198. }
  199. $out .= '</'.$this->nss.'Point>';
  200. return $out;
  201. }
  202. private function linestringToKML($geom, $type = FALSE) {
  203. if (!$type) {
  204. $type = $geom->getGeomType();
  205. }
  206. $str = '<'.$this->nss . $type .'>';
  207. if (!$geom->isEmpty()) {
  208. $str .= '<'.$this->nss.'coordinates>';
  209. $i=0;
  210. foreach ($geom->getComponents() as $comp) {
  211. if ($i != 0) $str .= ' ';
  212. $str .= $comp->getX() .','. $comp->getY();
  213. $i++;
  214. }
  215. $str .= '</'.$this->nss.'coordinates>';
  216. }
  217. $str .= '</'. $this->nss . $type .'>';
  218. return $str;
  219. }
  220. public function polygonToKML($geom) {
  221. $components = $geom->getComponents();
  222. $str = '';
  223. if (!empty($components)) {
  224. $str = '<'.$this->nss.'outerBoundaryIs>' . $this->linestringToKML($components[0], 'LinearRing') . '</'.$this->nss.'outerBoundaryIs>';
  225. foreach (array_slice($components, 1) as $comp) {
  226. $str .= '<'.$this->nss.'innerBoundaryIs>' . $this->linestringToKML($comp) . '</'.$this->nss.'innerBoundaryIs>';
  227. }
  228. }
  229. return '<'.$this->nss.'Polygon>'. $str .'</'.$this->nss.'Polygon>';
  230. }
  231. public function collectionToKML($geom) {
  232. $components = $geom->getComponents();
  233. $str = '<'.$this->nss.'MultiGeometry>';
  234. foreach ($geom->getComponents() as $comp) {
  235. $sub_adapter = new KML();
  236. $str .= $sub_adapter->write($comp);
  237. }
  238. return $str .'</'.$this->nss.'MultiGeometry>';
  239. }
  240. }