You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

geometries.py 24 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. """
  2. The OGRGeometry is a wrapper for using the OGR Geometry class
  3. (see http://www.gdal.org/classOGRGeometry.html). OGRGeometry
  4. may be instantiated when reading geometries from OGR Data Sources
  5. (e.g. SHP files), or when given OGC WKT (a string).
  6. While the 'full' API is not present yet, the API is "pythonic" unlike
  7. the traditional and "next-generation" OGR Python bindings. One major
  8. advantage OGR Geometries have over their GEOS counterparts is support
  9. for spatial reference systems and their transformation.
  10. Example:
  11. >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference
  12. >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)'
  13. >>> pnt = OGRGeometry(wkt1)
  14. >>> print(pnt)
  15. POINT (-90 30)
  16. >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84'))
  17. >>> mpnt.add(wkt1)
  18. >>> mpnt.add(wkt1)
  19. >>> print(mpnt)
  20. MULTIPOINT (-90 30,-90 30)
  21. >>> print(mpnt.srs.name)
  22. WGS 84
  23. >>> print(mpnt.srs.proj)
  24. +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
  25. >>> mpnt.transform_to(SpatialReference('NAD27'))
  26. >>> print(mpnt.proj)
  27. +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs
  28. >>> print(mpnt)
  29. MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641)
  30. The OGRGeomType class is to make it easy to specify an OGR geometry type:
  31. >>> from django.contrib.gis.gdal import OGRGeomType
  32. >>> gt1 = OGRGeomType(3) # Using an integer for the type
  33. >>> gt2 = OGRGeomType('Polygon') # Using a string
  34. >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
  35. >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
  36. True True
  37. """
  38. import sys
  39. from binascii import a2b_hex, b2a_hex
  40. from ctypes import byref, c_char_p, c_double, c_ubyte, c_void_p, string_at
  41. from django.contrib.gis.gdal.base import GDALBase
  42. from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
  43. from django.contrib.gis.gdal.error import (
  44. GDALException, OGRIndexError, SRSException,
  45. )
  46. from django.contrib.gis.gdal.geomtype import OGRGeomType
  47. from django.contrib.gis.gdal.prototypes import geom as capi, srs as srs_api
  48. from django.contrib.gis.gdal.srs import CoordTransform, SpatialReference
  49. from django.contrib.gis.geometry.regex import hex_regex, json_regex, wkt_regex
  50. from django.utils import six
  51. from django.utils.six.moves import range
  52. # For more information, see the OGR C API source code:
  53. # http://www.gdal.org/ogr__api_8h.html
  54. #
  55. # The OGR_G_* routines are relevant here.
  56. class OGRGeometry(GDALBase):
  57. "Generally encapsulates an OGR geometry."
  58. def __init__(self, geom_input, srs=None):
  59. "Initializes Geometry on either WKT or an OGR pointer as input."
  60. str_instance = isinstance(geom_input, six.string_types)
  61. # If HEX, unpack input to a binary buffer.
  62. if str_instance and hex_regex.match(geom_input):
  63. geom_input = six.memoryview(a2b_hex(geom_input.upper().encode()))
  64. str_instance = False
  65. # Constructing the geometry,
  66. if str_instance:
  67. wkt_m = wkt_regex.match(geom_input)
  68. json_m = json_regex.match(geom_input)
  69. if wkt_m:
  70. if wkt_m.group('srid'):
  71. # If there's EWKT, set the SRS w/value of the SRID.
  72. srs = int(wkt_m.group('srid'))
  73. if wkt_m.group('type').upper() == 'LINEARRING':
  74. # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT.
  75. # See http://trac.osgeo.org/gdal/ticket/1992.
  76. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num)
  77. capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt').encode())))
  78. else:
  79. g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt').encode())), None, byref(c_void_p()))
  80. elif json_m:
  81. g = capi.from_json(geom_input.encode())
  82. else:
  83. # Seeing if the input is a valid short-hand string
  84. # (e.g., 'Point', 'POLYGON').
  85. OGRGeomType(geom_input)
  86. g = capi.create_geom(OGRGeomType(geom_input).num)
  87. elif isinstance(geom_input, six.memoryview):
  88. # WKB was passed in
  89. g = capi.from_wkb(bytes(geom_input), None, byref(c_void_p()), len(geom_input))
  90. elif isinstance(geom_input, OGRGeomType):
  91. # OGRGeomType was passed in, an empty geometry will be created.
  92. g = capi.create_geom(geom_input.num)
  93. elif isinstance(geom_input, self.ptr_type):
  94. # OGR pointer (c_void_p) was the input.
  95. g = geom_input
  96. else:
  97. raise GDALException('Invalid input type for OGR Geometry construction: %s' % type(geom_input))
  98. # Now checking the Geometry pointer before finishing initialization
  99. # by setting the pointer for the object.
  100. if not g:
  101. raise GDALException('Cannot create OGR Geometry from input: %s' % str(geom_input))
  102. self.ptr = g
  103. # Assigning the SpatialReference object to the geometry, if valid.
  104. if srs:
  105. self.srs = srs
  106. # Setting the class depending upon the OGR Geometry Type
  107. self.__class__ = GEO_CLASSES[self.geom_type.num]
  108. def __del__(self):
  109. "Deletes this Geometry."
  110. if self._ptr and capi:
  111. capi.destroy_geom(self._ptr)
  112. # Pickle routines
  113. def __getstate__(self):
  114. srs = self.srs
  115. if srs:
  116. srs = srs.wkt
  117. else:
  118. srs = None
  119. return bytes(self.wkb), srs
  120. def __setstate__(self, state):
  121. wkb, srs = state
  122. ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb))
  123. if not ptr:
  124. raise GDALException('Invalid OGRGeometry loaded from pickled state.')
  125. self.ptr = ptr
  126. self.srs = srs
  127. @classmethod
  128. def from_bbox(cls, bbox):
  129. "Constructs a Polygon from a bounding box (4-tuple)."
  130. x0, y0, x1, y1 = bbox
  131. return OGRGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % (
  132. x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))
  133. # ### Geometry set-like operations ###
  134. # g = g1 | g2
  135. def __or__(self, other):
  136. "Returns the union of the two geometries."
  137. return self.union(other)
  138. # g = g1 & g2
  139. def __and__(self, other):
  140. "Returns the intersection of this Geometry and the other."
  141. return self.intersection(other)
  142. # g = g1 - g2
  143. def __sub__(self, other):
  144. "Return the difference this Geometry and the other."
  145. return self.difference(other)
  146. # g = g1 ^ g2
  147. def __xor__(self, other):
  148. "Return the symmetric difference of this Geometry and the other."
  149. return self.sym_difference(other)
  150. def __eq__(self, other):
  151. "Is this Geometry equal to the other?"
  152. if isinstance(other, OGRGeometry):
  153. return self.equals(other)
  154. else:
  155. return False
  156. def __ne__(self, other):
  157. "Tests for inequality."
  158. return not (self == other)
  159. def __str__(self):
  160. "WKT is used for the string representation."
  161. return self.wkt
  162. # #### Geometry Properties ####
  163. @property
  164. def dimension(self):
  165. "Returns 0 for points, 1 for lines, and 2 for surfaces."
  166. return capi.get_dims(self.ptr)
  167. def _get_coord_dim(self):
  168. "Returns the coordinate dimension of the Geometry."
  169. return capi.get_coord_dim(self.ptr)
  170. def _set_coord_dim(self, dim):
  171. "Sets the coordinate dimension of this Geometry."
  172. if dim not in (2, 3):
  173. raise ValueError('Geometry dimension must be either 2 or 3')
  174. capi.set_coord_dim(self.ptr, dim)
  175. coord_dim = property(_get_coord_dim, _set_coord_dim)
  176. @property
  177. def geom_count(self):
  178. "The number of elements in this Geometry."
  179. return capi.get_geom_count(self.ptr)
  180. @property
  181. def point_count(self):
  182. "Returns the number of Points in this Geometry."
  183. return capi.get_point_count(self.ptr)
  184. @property
  185. def num_points(self):
  186. "Alias for `point_count` (same name method in GEOS API.)"
  187. return self.point_count
  188. @property
  189. def num_coords(self):
  190. "Alais for `point_count`."
  191. return self.point_count
  192. @property
  193. def geom_type(self):
  194. "Returns the Type for this Geometry."
  195. return OGRGeomType(capi.get_geom_type(self.ptr))
  196. @property
  197. def geom_name(self):
  198. "Returns the Name of this Geometry."
  199. return capi.get_geom_name(self.ptr)
  200. @property
  201. def area(self):
  202. "Returns the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise."
  203. return capi.get_area(self.ptr)
  204. @property
  205. def envelope(self):
  206. "Returns the envelope for this Geometry."
  207. # TODO: Fix Envelope() for Point geometries.
  208. return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope())))
  209. @property
  210. def extent(self):
  211. "Returns the envelope as a 4-tuple, instead of as an Envelope object."
  212. return self.envelope.tuple
  213. # #### SpatialReference-related Properties ####
  214. # The SRS property
  215. def _get_srs(self):
  216. "Returns the Spatial Reference for this Geometry."
  217. try:
  218. srs_ptr = capi.get_geom_srs(self.ptr)
  219. return SpatialReference(srs_api.clone_srs(srs_ptr))
  220. except SRSException:
  221. return None
  222. def _set_srs(self, srs):
  223. "Sets the SpatialReference for this geometry."
  224. # Do not have to clone the `SpatialReference` object pointer because
  225. # when it is assigned to this `OGRGeometry` it's internal OGR
  226. # reference count is incremented, and will likewise be released
  227. # (decremented) when this geometry's destructor is called.
  228. if isinstance(srs, SpatialReference):
  229. srs_ptr = srs.ptr
  230. elif isinstance(srs, six.integer_types + six.string_types):
  231. sr = SpatialReference(srs)
  232. srs_ptr = sr.ptr
  233. else:
  234. raise TypeError('Cannot assign spatial reference with object of type: %s' % type(srs))
  235. capi.assign_srs(self.ptr, srs_ptr)
  236. srs = property(_get_srs, _set_srs)
  237. # The SRID property
  238. def _get_srid(self):
  239. srs = self.srs
  240. if srs:
  241. return srs.srid
  242. return None
  243. def _set_srid(self, srid):
  244. if isinstance(srid, six.integer_types):
  245. self.srs = srid
  246. else:
  247. raise TypeError('SRID must be set with an integer.')
  248. srid = property(_get_srid, _set_srid)
  249. # #### Output Methods ####
  250. @property
  251. def geos(self):
  252. "Returns a GEOSGeometry object from this OGRGeometry."
  253. from django.contrib.gis.geos import GEOSGeometry
  254. return GEOSGeometry(self.wkb, self.srid)
  255. @property
  256. def gml(self):
  257. "Returns the GML representation of the Geometry."
  258. return capi.to_gml(self.ptr)
  259. @property
  260. def hex(self):
  261. "Returns the hexadecimal representation of the WKB (a string)."
  262. return b2a_hex(self.wkb).upper()
  263. @property
  264. def json(self):
  265. """
  266. Returns the GeoJSON representation of this Geometry.
  267. """
  268. return capi.to_json(self.ptr)
  269. geojson = json
  270. @property
  271. def kml(self):
  272. "Returns the KML representation of the Geometry."
  273. return capi.to_kml(self.ptr, None)
  274. @property
  275. def wkb_size(self):
  276. "Returns the size of the WKB buffer."
  277. return capi.get_wkbsize(self.ptr)
  278. @property
  279. def wkb(self):
  280. "Returns the WKB representation of the Geometry."
  281. if sys.byteorder == 'little':
  282. byteorder = 1 # wkbNDR (from ogr_core.h)
  283. else:
  284. byteorder = 0 # wkbXDR
  285. sz = self.wkb_size
  286. # Creating the unsigned character buffer, and passing it in by reference.
  287. buf = (c_ubyte * sz)()
  288. capi.to_wkb(self.ptr, byteorder, byref(buf))
  289. # Returning a buffer of the string at the pointer.
  290. return six.memoryview(string_at(buf, sz))
  291. @property
  292. def wkt(self):
  293. "Returns the WKT representation of the Geometry."
  294. return capi.to_wkt(self.ptr, byref(c_char_p()))
  295. @property
  296. def ewkt(self):
  297. "Returns the EWKT representation of the Geometry."
  298. srs = self.srs
  299. if srs and srs.srid:
  300. return 'SRID=%s;%s' % (srs.srid, self.wkt)
  301. else:
  302. return self.wkt
  303. # #### Geometry Methods ####
  304. def clone(self):
  305. "Clones this OGR Geometry."
  306. return OGRGeometry(capi.clone_geom(self.ptr), self.srs)
  307. def close_rings(self):
  308. """
  309. If there are any rings within this geometry that have not been
  310. closed, this routine will do so by adding the starting point at the
  311. end.
  312. """
  313. # Closing the open rings.
  314. capi.geom_close_rings(self.ptr)
  315. def transform(self, coord_trans, clone=False):
  316. """
  317. Transforms this geometry to a different spatial reference system.
  318. May take a CoordTransform object, a SpatialReference object, string
  319. WKT or PROJ.4, and/or an integer SRID. By default nothing is returned
  320. and the geometry is transformed in-place. However, if the `clone`
  321. keyword is set, then a transformed clone of this geometry will be
  322. returned.
  323. """
  324. if clone:
  325. klone = self.clone()
  326. klone.transform(coord_trans)
  327. return klone
  328. # Depending on the input type, use the appropriate OGR routine
  329. # to perform the transformation.
  330. if isinstance(coord_trans, CoordTransform):
  331. capi.geom_transform(self.ptr, coord_trans.ptr)
  332. elif isinstance(coord_trans, SpatialReference):
  333. capi.geom_transform_to(self.ptr, coord_trans.ptr)
  334. elif isinstance(coord_trans, six.integer_types + six.string_types):
  335. sr = SpatialReference(coord_trans)
  336. capi.geom_transform_to(self.ptr, sr.ptr)
  337. else:
  338. raise TypeError('Transform only accepts CoordTransform, '
  339. 'SpatialReference, string, and integer objects.')
  340. def transform_to(self, srs):
  341. "For backwards-compatibility."
  342. self.transform(srs)
  343. # #### Topology Methods ####
  344. def _topology(self, func, other):
  345. """A generalized function for topology operations, takes a GDAL function and
  346. the other geometry to perform the operation on."""
  347. if not isinstance(other, OGRGeometry):
  348. raise TypeError('Must use another OGRGeometry object for topology operations!')
  349. # Returning the output of the given function with the other geometry's
  350. # pointer.
  351. return func(self.ptr, other.ptr)
  352. def intersects(self, other):
  353. "Returns True if this geometry intersects with the other."
  354. return self._topology(capi.ogr_intersects, other)
  355. def equals(self, other):
  356. "Returns True if this geometry is equivalent to the other."
  357. return self._topology(capi.ogr_equals, other)
  358. def disjoint(self, other):
  359. "Returns True if this geometry and the other are spatially disjoint."
  360. return self._topology(capi.ogr_disjoint, other)
  361. def touches(self, other):
  362. "Returns True if this geometry touches the other."
  363. return self._topology(capi.ogr_touches, other)
  364. def crosses(self, other):
  365. "Returns True if this geometry crosses the other."
  366. return self._topology(capi.ogr_crosses, other)
  367. def within(self, other):
  368. "Returns True if this geometry is within the other."
  369. return self._topology(capi.ogr_within, other)
  370. def contains(self, other):
  371. "Returns True if this geometry contains the other."
  372. return self._topology(capi.ogr_contains, other)
  373. def overlaps(self, other):
  374. "Returns True if this geometry overlaps the other."
  375. return self._topology(capi.ogr_overlaps, other)
  376. # #### Geometry-generation Methods ####
  377. def _geomgen(self, gen_func, other=None):
  378. "A helper routine for the OGR routines that generate geometries."
  379. if isinstance(other, OGRGeometry):
  380. return OGRGeometry(gen_func(self.ptr, other.ptr), self.srs)
  381. else:
  382. return OGRGeometry(gen_func(self.ptr), self.srs)
  383. @property
  384. def boundary(self):
  385. "Returns the boundary of this geometry."
  386. return self._geomgen(capi.get_boundary)
  387. @property
  388. def convex_hull(self):
  389. """
  390. Returns the smallest convex Polygon that contains all the points in
  391. this Geometry.
  392. """
  393. return self._geomgen(capi.geom_convex_hull)
  394. def difference(self, other):
  395. """
  396. Returns a new geometry consisting of the region which is the difference
  397. of this geometry and the other.
  398. """
  399. return self._geomgen(capi.geom_diff, other)
  400. def intersection(self, other):
  401. """
  402. Returns a new geometry consisting of the region of intersection of this
  403. geometry and the other.
  404. """
  405. return self._geomgen(capi.geom_intersection, other)
  406. def sym_difference(self, other):
  407. """
  408. Returns a new geometry which is the symmetric difference of this
  409. geometry and the other.
  410. """
  411. return self._geomgen(capi.geom_sym_diff, other)
  412. def union(self, other):
  413. """
  414. Returns a new geometry consisting of the region which is the union of
  415. this geometry and the other.
  416. """
  417. return self._geomgen(capi.geom_union, other)
  418. # The subclasses for OGR Geometry.
  419. class Point(OGRGeometry):
  420. @property
  421. def x(self):
  422. "Returns the X coordinate for this Point."
  423. return capi.getx(self.ptr, 0)
  424. @property
  425. def y(self):
  426. "Returns the Y coordinate for this Point."
  427. return capi.gety(self.ptr, 0)
  428. @property
  429. def z(self):
  430. "Returns the Z coordinate for this Point."
  431. if self.coord_dim == 3:
  432. return capi.getz(self.ptr, 0)
  433. @property
  434. def tuple(self):
  435. "Returns the tuple of this point."
  436. if self.coord_dim == 2:
  437. return (self.x, self.y)
  438. elif self.coord_dim == 3:
  439. return (self.x, self.y, self.z)
  440. coords = tuple
  441. class LineString(OGRGeometry):
  442. def __getitem__(self, index):
  443. "Returns the Point at the given index."
  444. if index >= 0 and index < self.point_count:
  445. x, y, z = c_double(), c_double(), c_double()
  446. capi.get_point(self.ptr, index, byref(x), byref(y), byref(z))
  447. dim = self.coord_dim
  448. if dim == 1:
  449. return (x.value,)
  450. elif dim == 2:
  451. return (x.value, y.value)
  452. elif dim == 3:
  453. return (x.value, y.value, z.value)
  454. else:
  455. raise OGRIndexError('index out of range: %s' % str(index))
  456. def __iter__(self):
  457. "Iterates over each point in the LineString."
  458. for i in range(self.point_count):
  459. yield self[i]
  460. def __len__(self):
  461. "The length returns the number of points in the LineString."
  462. return self.point_count
  463. @property
  464. def tuple(self):
  465. "Returns the tuple representation of this LineString."
  466. return tuple(self[i] for i in range(len(self)))
  467. coords = tuple
  468. def _listarr(self, func):
  469. """
  470. Internal routine that returns a sequence (list) corresponding with
  471. the given function.
  472. """
  473. return [func(self.ptr, i) for i in range(len(self))]
  474. @property
  475. def x(self):
  476. "Returns the X coordinates in a list."
  477. return self._listarr(capi.getx)
  478. @property
  479. def y(self):
  480. "Returns the Y coordinates in a list."
  481. return self._listarr(capi.gety)
  482. @property
  483. def z(self):
  484. "Returns the Z coordinates in a list."
  485. if self.coord_dim == 3:
  486. return self._listarr(capi.getz)
  487. # LinearRings are used in Polygons.
  488. class LinearRing(LineString):
  489. pass
  490. class Polygon(OGRGeometry):
  491. def __len__(self):
  492. "The number of interior rings in this Polygon."
  493. return self.geom_count
  494. def __iter__(self):
  495. "Iterates through each ring in the Polygon."
  496. for i in range(self.geom_count):
  497. yield self[i]
  498. def __getitem__(self, index):
  499. "Gets the ring at the specified index."
  500. if index < 0 or index >= self.geom_count:
  501. raise OGRIndexError('index out of range: %s' % index)
  502. else:
  503. return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs)
  504. # Polygon Properties
  505. @property
  506. def shell(self):
  507. "Returns the shell of this Polygon."
  508. return self[0] # First ring is the shell
  509. exterior_ring = shell
  510. @property
  511. def tuple(self):
  512. "Returns a tuple of LinearRing coordinate tuples."
  513. return tuple(self[i].tuple for i in range(self.geom_count))
  514. coords = tuple
  515. @property
  516. def point_count(self):
  517. "The number of Points in this Polygon."
  518. # Summing up the number of points in each ring of the Polygon.
  519. return sum(self[i].point_count for i in range(self.geom_count))
  520. @property
  521. def centroid(self):
  522. "Returns the centroid (a Point) of this Polygon."
  523. # The centroid is a Point, create a geometry for this.
  524. p = OGRGeometry(OGRGeomType('Point'))
  525. capi.get_centroid(self.ptr, p.ptr)
  526. return p
  527. # Geometry Collection base class.
  528. class GeometryCollection(OGRGeometry):
  529. "The Geometry Collection class."
  530. def __getitem__(self, index):
  531. "Gets the Geometry at the specified index."
  532. if index < 0 or index >= self.geom_count:
  533. raise OGRIndexError('index out of range: %s' % index)
  534. else:
  535. return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs)
  536. def __iter__(self):
  537. "Iterates over each Geometry."
  538. for i in range(self.geom_count):
  539. yield self[i]
  540. def __len__(self):
  541. "The number of geometries in this Geometry Collection."
  542. return self.geom_count
  543. def add(self, geom):
  544. "Add the geometry to this Geometry Collection."
  545. if isinstance(geom, OGRGeometry):
  546. if isinstance(geom, self.__class__):
  547. for g in geom:
  548. capi.add_geom(self.ptr, g.ptr)
  549. else:
  550. capi.add_geom(self.ptr, geom.ptr)
  551. elif isinstance(geom, six.string_types):
  552. tmp = OGRGeometry(geom)
  553. capi.add_geom(self.ptr, tmp.ptr)
  554. else:
  555. raise GDALException('Must add an OGRGeometry.')
  556. @property
  557. def point_count(self):
  558. "The number of Points in this Geometry Collection."
  559. # Summing up the number of points in each geometry in this collection
  560. return sum(self[i].point_count for i in range(self.geom_count))
  561. @property
  562. def tuple(self):
  563. "Returns a tuple representation of this Geometry Collection."
  564. return tuple(self[i].tuple for i in range(self.geom_count))
  565. coords = tuple
  566. # Multiple Geometry types.
  567. class MultiPoint(GeometryCollection):
  568. pass
  569. class MultiLineString(GeometryCollection):
  570. pass
  571. class MultiPolygon(GeometryCollection):
  572. pass
  573. # Class mapping dictionary (using the OGRwkbGeometryType as the key)
  574. GEO_CLASSES = {1: Point,
  575. 2: LineString,
  576. 3: Polygon,
  577. 4: MultiPoint,
  578. 5: MultiLineString,
  579. 6: MultiPolygon,
  580. 7: GeometryCollection,
  581. 101: LinearRing,
  582. 1 + OGRGeomType.wkb25bit: Point,
  583. 2 + OGRGeomType.wkb25bit: LineString,
  584. 3 + OGRGeomType.wkb25bit: Polygon,
  585. 4 + OGRGeomType.wkb25bit: MultiPoint,
  586. 5 + OGRGeomType.wkb25bit: MultiLineString,
  587. 6 + OGRGeomType.wkb25bit: MultiPolygon,
  588. 7 + OGRGeomType.wkb25bit: GeometryCollection,
  589. }