/django/contrib/gis/gdal/geometries.py

https://code.google.com/p/mango-py/ · Python · 737 lines · 600 code · 52 blank · 85 comment · 63 complexity · 57f6ba2506e280077fa215a635460121 MD5 · raw file

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