EWKB.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * EWKB (Extended Well Known Binary) Adapter
  4. */
  5. class EWKB extends WKB
  6. {
  7. /**
  8. * Read WKB binary string into geometry objects
  9. *
  10. * @param string $wkb An Extended-WKB binary string
  11. *
  12. * @return Geometry
  13. */
  14. public function read($wkb, $is_hex_string = FALSE) {
  15. if ($is_hex_string) {
  16. $wkb = pack('H*',$wkb);
  17. }
  18. // Open the wkb up in memory so we can examine the SRID
  19. $mem = fopen('php://memory', 'r+');
  20. fwrite($mem, $wkb);
  21. fseek($mem, 0);
  22. $base_info = unpack("corder/ctype/cz/cm/cs", fread($mem, 5));
  23. if ($base_info['s']) {
  24. $srid = current(unpack("Lsrid", fread($mem, 4)));
  25. }
  26. else {
  27. $srid = NULL;
  28. }
  29. fclose($mem);
  30. // Run the wkb through the normal WKB reader to get the geometry
  31. $wkb_reader = new WKB();
  32. $geom = $wkb_reader->read($wkb);
  33. // If there is an SRID, add it to the geometry
  34. if ($srid) {
  35. $geom->setSRID($srid);
  36. }
  37. return $geom;
  38. }
  39. /**
  40. * Serialize geometries into an EWKB binary string.
  41. *
  42. * @param Geometry $geometry
  43. *
  44. * @return string The Extended-WKB binary string representation of the input geometries
  45. */
  46. public function write(Geometry $geometry, $write_as_hex = FALSE) {
  47. // We always write into NDR (little endian)
  48. $wkb = pack('c',1);
  49. switch ($geometry->getGeomType()) {
  50. case 'Point';
  51. $wkb .= pack('L',1);
  52. $wkb .= $this->writePoint($geometry);
  53. break;
  54. case 'LineString';
  55. $wkb .= pack('L',2);
  56. $wkb .= $this->writeLineString($geometry);
  57. break;
  58. case 'Polygon';
  59. $wkb .= pack('L',3);
  60. $wkb .= $this->writePolygon($geometry);
  61. break;
  62. case 'MultiPoint';
  63. $wkb .= pack('L',4);
  64. $wkb .= $this->writeMulti($geometry);
  65. break;
  66. case 'MultiLineString';
  67. $wkb .= pack('L',5);
  68. $wkb .= $this->writeMulti($geometry);
  69. break;
  70. case 'MultiPolygon';
  71. $wkb .= pack('L',6);
  72. $wkb .= $this->writeMulti($geometry);
  73. break;
  74. case 'GeometryCollection';
  75. $wkb .= pack('L',7);
  76. $wkb .= $this->writeMulti($geometry);
  77. break;
  78. }
  79. if ($write_as_hex) {
  80. $unpacked = unpack('H*',$wkb);
  81. return $unpacked[1];
  82. }
  83. else {
  84. return $wkb;
  85. }
  86. }
  87. }