geometries.py 27 KB

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