geometries.py 25 KB

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