geometries.py 24 KB

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