geometries.py 24 KB

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