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 24KB

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