geos.txt 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. ========
  2. GEOS API
  3. ========
  4. .. module:: django.contrib.gis.geos
  5. :synopsis: GeoDjango's high-level interface to the GEOS library.
  6. Background
  7. ==========
  8. What is GEOS?
  9. -------------
  10. `GEOS`__ stands for **Geometry Engine - Open Source**,
  11. and is a C++ library, ported from the `Java Topology Suite`__. GEOS
  12. implements the OpenGIS `Simple Features for SQL`__ spatial predicate functions
  13. and spatial operators. GEOS, now an OSGeo project, was initially developed and
  14. maintained by `Refractions Research`__ of Victoria, Canada.
  15. __ http://trac.osgeo.org/geos/
  16. __ http://sourceforge.net/projects/jts-topo-suite/
  17. __ http://www.opengeospatial.org/standards/sfs
  18. __ http://www.refractions.net/
  19. Features
  20. --------
  21. GeoDjango implements a high-level Python wrapper for the GEOS library, its
  22. features include:
  23. * A BSD-licensed interface to the GEOS geometry routines, implemented purely
  24. in Python using ``ctypes``.
  25. * Loosely-coupled to GeoDjango. For example, :class:`GEOSGeometry` objects
  26. may be used outside of a Django project/application. In other words,
  27. no need to have ``DJANGO_SETTINGS_MODULE`` set or use a database, etc.
  28. * Mutability: :class:`GEOSGeometry` objects may be modified.
  29. * Cross-platform and tested; compatible with Windows, Linux, Solaris, and Mac
  30. OS X platforms.
  31. .. _geos-tutorial:
  32. Tutorial
  33. ========
  34. This section contains a brief introduction and tutorial to using
  35. :class:`GEOSGeometry` objects.
  36. Creating a Geometry
  37. -------------------
  38. :class:`GEOSGeometry` objects may be created in a few ways. The first is
  39. to simply instantiate the object on some spatial input -- the following
  40. are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON::
  41. >>> from django.contrib.gis.geos import GEOSGeometry
  42. >>> pnt = GEOSGeometry('POINT(5 23)') # WKT
  43. >>> pnt = GEOSGeometry('010100000000000000000014400000000000003740') # HEX
  44. >>> pnt = GEOSGeometry(buffer('\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x007@'))
  45. >>> pnt = GEOSGeometry('{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }') # GeoJSON
  46. Another option is to use the constructor for the specific geometry type
  47. that you wish to create. For example, a :class:`Point` object may be
  48. created by passing in the X and Y coordinates into its constructor::
  49. >>> from django.contrib.gis.geos import Point
  50. >>> pnt = Point(5, 23)
  51. Finally, there are :func:`fromstr` and :func:`fromfile` factory methods, which
  52. return a :class:`GEOSGeometry` object from an input string or a file::
  53. >>> from django.contrib.gis.geos import fromstr, fromfile
  54. >>> pnt = fromstr('POINT(5 23)')
  55. >>> pnt = fromfile('/path/to/pnt.wkt')
  56. >>> pnt = fromfile(open('/path/to/pnt.wkt'))
  57. .. _geos-exceptions-in-logfile:
  58. .. admonition:: My logs are filled with GEOS-related errors
  59. You find many ``TypeError`` or ``AttributeError`` exceptions filling your
  60. Web server's log files. This generally means that you are creating GEOS
  61. objects at the top level of some of your Python modules. Then, due to a race
  62. condition in the garbage collector, your module is garbage collected before
  63. the GEOS object. To prevent this, create :class:`GEOSGeometry` objects
  64. inside the local scope of your functions/methods.
  65. Geometries are Pythonic
  66. -----------------------
  67. :class:`GEOSGeometry` objects are 'Pythonic', in other words components may
  68. be accessed, modified, and iterated over using standard Python conventions.
  69. For example, you can iterate over the coordinates in a :class:`Point`::
  70. >>> pnt = Point(5, 23)
  71. >>> [coord for coord in pnt]
  72. [5.0, 23.0]
  73. With any geometry object, the :attr:`GEOSGeometry.coords` property
  74. may be used to get the geometry coordinates as a Python tuple::
  75. >>> pnt.coords
  76. (5.0, 23.0)
  77. You can get/set geometry components using standard Python indexing
  78. techniques. However, what is returned depends on the geometry type
  79. of the object. For example, indexing on a :class:`LineString`
  80. returns a coordinate tuple::
  81. >>> from django.contrib.gis.geos import LineString
  82. >>> line = LineString((0, 0), (0, 50), (50, 50), (50, 0), (0, 0))
  83. >>> line[0]
  84. (0.0, 0.0)
  85. >>> line[-2]
  86. (50.0, 0.0)
  87. Whereas indexing on a :class:`Polygon` will return the ring
  88. (a :class:`LinearRing` object) corresponding to the index::
  89. >>> from django.contrib.gis.geos import Polygon
  90. >>> poly = Polygon( ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)) )
  91. >>> poly[0]
  92. <LinearRing object at 0x1044395b0>
  93. >>> poly[0][-2] # second-to-last coordinate of external ring
  94. (50.0, 0.0)
  95. In addition, coordinates/components of the geometry may added or modified,
  96. just like a Python list::
  97. >>> line[0] = (1.0, 1.0)
  98. >>> line.pop()
  99. (0.0, 0.0)
  100. >>> line.append((1.0, 1.0))
  101. >>> line.coords
  102. ((1.0, 1.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (1.0, 1.0))
  103. Geometry Objects
  104. ================
  105. ``GEOSGeometry``
  106. ----------------
  107. .. class:: GEOSGeometry(geo_input[, srid=None])
  108. :param geo_input: Geometry input value (string or buffer)
  109. :param srid: spatial reference identifier
  110. :type srid: int
  111. This is the base class for all GEOS geometry objects. It initializes on the
  112. given ``geo_input`` argument, and then assumes the proper geometry subclass
  113. (e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object).
  114. The following input formats, along with their corresponding Python types,
  115. are accepted:
  116. ============= ======================
  117. Format Input Type
  118. ============= ======================
  119. WKT / EWKT ``str`` or ``unicode``
  120. HEX / HEXEWKB ``str`` or ``unicode``
  121. WKB / EWKB ``buffer``
  122. GeoJSON ``str`` or ``unicode``
  123. ============= ======================
  124. .. note::
  125. The new 3D/4D WKT notation with an intermediary Z or M (like
  126. ``POINT Z (3, 4, 5)``) is only supported with GEOS 3.3.0 or later.
  127. Properties
  128. ~~~~~~~~~~
  129. .. attribute:: GEOSGeometry.coords
  130. Returns the coordinates of the geometry as a tuple.
  131. .. attribute:: GEOSGeometry.empty
  132. Returns whether or not the set of points in the geometry is empty.
  133. .. attribute:: GEOSGeometry.geom_type
  134. Returns a string corresponding to the type of geometry. For example::
  135. >>> pnt = GEOSGeometry('POINT(5 23)')
  136. >>> pnt.geom_type
  137. 'Point'
  138. .. attribute:: GEOSGeometry.geom_typeid
  139. Returns the GEOS geometry type identification number. The following table
  140. shows the value for each geometry type:
  141. =========================== ========
  142. Geometry ID
  143. =========================== ========
  144. :class:`Point` 0
  145. :class:`LineString` 1
  146. :class:`LinearRing` 2
  147. :class:`Polygon` 3
  148. :class:`MultiPoint` 4
  149. :class:`MultiLineString` 5
  150. :class:`MultiPolygon` 6
  151. :class:`GeometryCollection` 7
  152. =========================== ========
  153. .. attribute:: GEOSGeometry.num_coords
  154. Returns the number of coordinates in the geometry.
  155. .. attribute:: GEOSGeometry.num_geom
  156. Returns the number of geometries in this geometry. In other words, will
  157. return 1 on anything but geometry collections.
  158. .. attribute:: GEOSGeometry.hasz
  159. Returns a boolean indicating whether the geometry is three-dimensional.
  160. .. attribute:: GEOSGeometry.ring
  161. Returns a boolean indicating whether the geometry is a ``LinearRing``.
  162. .. attribute:: GEOSGeometry.simple
  163. Returns a boolean indicating whether the geometry is 'simple'. A geometry
  164. is simple if and only if it does not intersect itself (except at boundary
  165. points). For example, a :class:`LineString` object is not simple if it
  166. intersects itself. Thus, :class:`LinearRing` and :class:`Polygon` objects
  167. are always simple because they do cannot intersect themselves, by
  168. definition.
  169. .. attribute:: GEOSGeometry.valid
  170. Returns a boolean indicating whether the geometry is valid.
  171. .. attribute:: GEOSGeometry.valid_reason
  172. Returns a string describing the reason why a geometry is invalid.
  173. .. attribute:: GEOSGeometry.srid
  174. Property that may be used to retrieve or set the SRID associated with the
  175. geometry. For example::
  176. >>> pnt = Point(5, 23)
  177. >>> print(pnt.srid)
  178. None
  179. >>> pnt.srid = 4326
  180. >>> pnt.srid
  181. 4326
  182. Output Properties
  183. ~~~~~~~~~~~~~~~~~
  184. The properties in this section export the :class:`GEOSGeometry` object into
  185. a different. This output may be in the form of a string, buffer, or even
  186. another object.
  187. .. attribute:: GEOSGeometry.ewkt
  188. Returns the "extended" Well-Known Text of the geometry. This representation
  189. is specific to PostGIS and is a super set of the OGC WKT standard. [#fnogc]_
  190. Essentially the SRID is prepended to the WKT representation, for example
  191. ``SRID=4326;POINT(5 23)``.
  192. .. note::
  193. The output from this property does not include the 3dm, 3dz, and 4d
  194. information that PostGIS supports in its EWKT representations.
  195. .. attribute:: GEOSGeometry.hex
  196. Returns the WKB of this Geometry in hexadecimal form. Please note
  197. that the SRID value is not included in this representation
  198. because it is not a part of the OGC specification (use the
  199. :attr:`GEOSGeometry.hexewkb` property instead).
  200. .. attribute:: GEOSGeometry.hexewkb
  201. Returns the EWKB of this Geometry in hexadecimal form. This is an
  202. extension of the WKB specification that includes the SRID value
  203. that are a part of this geometry.
  204. .. attribute:: GEOSGeometry.json
  205. Returns the GeoJSON representation of the geometry.
  206. .. note::
  207. Requires GDAL.
  208. .. attribute:: GEOSGeometry.geojson
  209. Alias for :attr:`GEOSGeometry.json`.
  210. .. attribute:: GEOSGeometry.kml
  211. Returns a `KML`__ (Keyhole Markup Language) representation of the
  212. geometry. This should only be used for geometries with an SRID of
  213. 4326 (WGS84), but this restriction is not enforced.
  214. .. attribute:: GEOSGeometry.ogr
  215. Returns an :class:`~django.contrib.gis.gdal.OGRGeometry` object
  216. corresponding to the GEOS geometry.
  217. .. note::
  218. Requires GDAL.
  219. .. _wkb:
  220. .. attribute:: GEOSGeometry.wkb
  221. Returns the WKB (Well-Known Binary) representation of this Geometry
  222. as a Python buffer. SRID value is not included, use the
  223. :attr:`GEOSGeometry.ewkb` property instead.
  224. .. _ewkb:
  225. .. attribute:: GEOSGeometry.ewkb
  226. Return the EWKB representation of this Geometry as a Python buffer.
  227. This is an extension of the WKB specification that includes any SRID
  228. value that are a part of this geometry.
  229. .. attribute:: GEOSGeometry.wkt
  230. Returns the Well-Known Text of the geometry (an OGC standard).
  231. __ https://developers.google.com/kml/documentation/
  232. Spatial Predicate Methods
  233. ~~~~~~~~~~~~~~~~~~~~~~~~~
  234. All of the following spatial predicate methods take another
  235. :class:`GEOSGeometry` instance (``other``) as a parameter, and
  236. return a boolean.
  237. .. method:: GEOSGeometry.contains(other)
  238. Returns ``True`` if :meth:`GEOSGeometry.within` is ``False``.
  239. .. method:: GEOSGeometry.crosses(other)
  240. Returns ``True`` if the DE-9IM intersection matrix for the two Geometries
  241. is ``T*T******`` (for a point and a curve,a point and an area or a line
  242. and an area) ``0********`` (for two curves).
  243. .. method:: GEOSGeometry.disjoint(other)
  244. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  245. is ``FF*FF****``.
  246. .. method:: GEOSGeometry.equals(other)
  247. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  248. is ``T*F**FFF*``.
  249. .. method:: GEOSGeometry.equals_exact(other, tolerance=0)
  250. Returns true if the two geometries are exactly equal, up to a
  251. specified tolerance. The ``tolerance`` value should be a floating
  252. point number representing the error tolerance in the comparison, e.g.,
  253. ``poly1.equals_exact(poly2, 0.001)`` will compare equality to within
  254. one thousandth of a unit.
  255. .. method:: GEOSGeometry.intersects(other)
  256. Returns ``True`` if :meth:`GEOSGeometry.disjoint` is ``False``.
  257. .. method:: GEOSGeometry.overlaps(other)
  258. Returns true if the DE-9IM intersection matrix for the two geometries
  259. is ``T*T***T**`` (for two points or two surfaces) ``1*T***T**``
  260. (for two curves).
  261. .. method:: GEOSGeometry.relate_pattern(other, pattern)
  262. Returns ``True`` if the elements in the DE-9IM intersection matrix
  263. for this geometry and the other matches the given ``pattern`` --
  264. a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
  265. .. method:: GEOSGeometry.touches(other)
  266. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  267. is ``FT*******``, ``F**T*****`` or ``F***T****``.
  268. .. method:: GEOSGeometry.within(other)
  269. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  270. is ``T*F**F***``.
  271. Topological Methods
  272. ~~~~~~~~~~~~~~~~~~~
  273. .. method:: GEOSGeometry.buffer(width, quadsegs=8)
  274. Returns a :class:`GEOSGeometry` that represents all points whose distance
  275. from this geometry is less than or equal to the given ``width``. The optional
  276. ``quadsegs`` keyword sets the number of segments used to approximate a
  277. quarter circle (defaults is 8).
  278. .. method:: GEOSGeometry.difference(other)
  279. Returns a :class:`GEOSGeometry` representing the points making up this
  280. geometry that do not make up other.
  281. .. method:: GEOSGeometry.interpolate(distance)
  282. .. method:: GEOSGeometry.interpolate_normalized(distance)
  283. Given a distance (float), returns the point (or closest point) within the
  284. geometry (:class:`LineString` or :class:`MultiLineString`) at that distance.
  285. The normalized version takes the distance as a float between 0 (origin) and 1
  286. (endpoint).
  287. Reverse of :meth:`GEOSGeometry.project`.
  288. .. method:: GEOSGeometry:intersection(other)
  289. Returns a :class:`GEOSGeometry` representing the points shared by this
  290. geometry and other.
  291. .. method:: GEOSGeometry.project(point)
  292. .. method:: GEOSGeometry.project_normalized(point)
  293. Returns the distance (float) from the origin of the geometry
  294. (:class:`LineString` or :class:`MultiLineString`) to the point projected on the
  295. geometry (that is to a point of the line the closest to the given point).
  296. The normalized version returns the distance as a float between 0 (origin) and 1
  297. (endpoint).
  298. Reverse of :meth:`GEOSGeometry.interpolate`.
  299. .. method:: GEOSGeometry.relate(other)
  300. Returns the DE-9IM intersection matrix (a string) representing the
  301. topological relationship between this geometry and the other.
  302. .. method:: GEOSGeometry.simplify(tolerance=0.0, preserve_topology=False)
  303. Returns a new :class:`GEOSGeometry`, simplified to the specified tolerance
  304. using the Douglas-Peucker algorithm. A higher tolerance value implies
  305. fewer points in the output. If no tolerance is provided, it defaults to 0.
  306. By default, this function does not preserve topology. For example,
  307. :class:`Polygon` objects can be split, be collapsed into lines, or disappear.
  308. :class:`Polygon` holes can be created or disappear, and lines may cross.
  309. By specifying ``preserve_topology=True``, the result will have the same
  310. dimension and number of components as the input; this is significantly
  311. slower, however.
  312. .. method:: GEOSGeometry.sym_difference(other)
  313. Returns a :class:`GEOSGeometry` combining the points in this geometry
  314. not in other, and the points in other not in this geometry.
  315. .. method:: GEOSGeometry.union(other)
  316. Returns a :class:`GEOSGeometry` representing all the points in this
  317. geometry and the other.
  318. Topological Properties
  319. ~~~~~~~~~~~~~~~~~~~~~~
  320. .. attribute:: GEOSGeometry.boundary
  321. Returns the boundary as a newly allocated Geometry object.
  322. .. attribute:: GEOSGeometry.centroid
  323. Returns a :class:`Point` object representing the geometric center of
  324. the geometry. The point is not guaranteed to be on the interior
  325. of the geometry.
  326. .. attribute:: GEOSGeometry.convex_hull
  327. Returns the smallest :class:`Polygon` that contains all the points in
  328. the geometry.
  329. .. attribute:: GEOSGeometry.envelope
  330. Returns a :class:`Polygon` that represents the bounding envelope of
  331. this geometry.
  332. .. attribute:: GEOSGeometry.point_on_surface
  333. Computes and returns a :class:`Point` guaranteed to be on the interior
  334. of this geometry.
  335. Other Properties & Methods
  336. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  337. .. attribute:: GEOSGeometry.area
  338. This property returns the area of the Geometry.
  339. .. attribute:: GEOSGeometry.extent
  340. This property returns the extent of this geometry as a 4-tuple,
  341. consisting of ``(xmin, ymin, xmax, ymax)``.
  342. .. method:: GEOSGeometry.clone()
  343. This method returns a :class:`GEOSGeometry` that is a clone of the original.
  344. .. method:: GEOSGeometry.distance(geom)
  345. Returns the distance between the closest points on this geometry and the given
  346. ``geom`` (another :class:`GEOSGeometry` object).
  347. .. note::
  348. GEOS distance calculations are linear -- in other words, GEOS does not
  349. perform a spherical calculation even if the SRID specifies a geographic
  350. coordinate system.
  351. .. attribute:: GEOSGeometry.length
  352. Returns the length of this geometry (e.g., 0 for a :class:`Point`,
  353. the length of a :class:`LineString`, or the circumference of
  354. a :class:`Polygon`).
  355. .. attribute:: GEOSGeometry.prepared
  356. Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.
  357. ``PreparedGeometry`` objects are optimized for the contains, intersects,
  358. covers, crosses, disjoint, overlaps, touches and within operations. Refer to
  359. the :ref:`prepared-geometries` documentation for more information.
  360. .. attribute:: GEOSGeometry.srs
  361. Returns a :class:`~django.contrib.gis.gdal.SpatialReference` object
  362. corresponding to the SRID of the geometry or ``None``.
  363. .. note::
  364. Requires GDAL.
  365. .. method:: GEOSGeometry.transform(ct, clone=False)
  366. Transforms the geometry according to the given coordinate transformation parameter
  367. (``ct``), which may be an integer SRID, spatial reference WKT string,
  368. a PROJ.4 string, a :class:`~django.contrib.gis.gdal.SpatialReference` object, or a
  369. :class:`~django.contrib.gis.gdal.CoordTransform` object. By default, the geometry
  370. is transformed in-place and nothing is returned. However if the ``clone`` keyword
  371. is set, then the geometry is not modified and a transformed clone of the geometry
  372. is returned instead.
  373. .. note::
  374. Requires GDAL. Raises :class:`~django.contrib.gis.geos.GEOSException` if
  375. GDAL is not available or if the SRID is ``None`` or less than 0.
  376. ``Point``
  377. ---------
  378. .. class:: Point(x, y, z=None, srid=None)
  379. ``Point`` objects are instantiated using arguments that represent
  380. the component coordinates of the point or with a single sequence
  381. coordinates. For example, the following are equivalent::
  382. >>> pnt = Point(5, 23)
  383. >>> pnt = Point([5, 23])
  384. ``LineString``
  385. --------------
  386. .. class:: LineString(*args, **kwargs)
  387. ``LineString`` objects are instantiated using arguments that are
  388. either a sequence of coordinates or :class:`Point` objects.
  389. For example, the following are equivalent::
  390. >>> ls = LineString((0, 0), (1, 1))
  391. >>> ls = LineString(Point(0, 0), Point(1, 1))
  392. In addition, ``LineString`` objects may also be created by passing
  393. in a single sequence of coordinate or :class:`Point` objects::
  394. >>> ls = LineString( ((0, 0), (1, 1)) )
  395. >>> ls = LineString( [Point(0, 0), Point(1, 1)] )
  396. ``LinearRing``
  397. --------------
  398. .. class:: LinearRing(*args, **kwargs)
  399. ``LinearRing`` objects are constructed in the exact same way as
  400. :class:`LineString` objects, however the coordinates must be
  401. *closed*, in other words, the first coordinates must be the
  402. same as the last coordinates. For example::
  403. >>> ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))
  404. Notice that ``(0, 0)`` is the first and last coordinate -- if
  405. they were not equal, an error would be raised.
  406. ``Polygon``
  407. -----------
  408. .. class:: Polygon(*args, **kwargs)
  409. ``Polygon`` objects may be instantiated by passing in one or
  410. more parameters that represent the rings of the polygon. The
  411. parameters must either be :class:`LinearRing` instances, or
  412. a sequence that may be used to construct a :class:`LinearRing`::
  413. >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
  414. >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))
  415. >>> poly = Polygon(ext_coords, int_coords)
  416. >>> poly = Polygon(LinearRing(ext_coords), LinearRing(int_coords))
  417. .. classmethod:: from_bbox(bbox)
  418. Returns a polygon object from the given bounding-box, a 4-tuple
  419. comprising ``(xmin, ymin, xmax, ymax)``.
  420. .. attribute:: num_interior_rings
  421. Returns the number of interior rings in this geometry.
  422. .. admonition:: Comparing Polygons
  423. Note that it is possible to compare ``Polygon`` objects directly with ``<``
  424. or ``>``, but as the comparison is made through Polygon's
  425. :class:`LineString`, it does not mean much (but is consistent and quick).
  426. You can always force the comparison with the :attr:`~GEOSGeometry.area`
  427. property::
  428. >>> if poly_1.area > poly_2.area:
  429. >>> pass
  430. Geometry Collections
  431. ====================
  432. ``MultiPoint``
  433. --------------
  434. .. class:: MultiPoint(*args, **kwargs)
  435. ``MultiPoint`` objects may be instantiated by passing in one
  436. or more :class:`Point` objects as arguments, or a single
  437. sequence of :class:`Point` objects::
  438. >>> mp = MultiPoint(Point(0, 0), Point(1, 1))
  439. >>> mp = MultiPoint( (Point(0, 0), Point(1, 1)) )
  440. ``MultiLineString``
  441. -------------------
  442. .. class:: MultiLineString(*args, **kwargs)
  443. ``MultiLineString`` objects may be instantiated by passing in one
  444. or more :class:`LineString` objects as arguments, or a single
  445. sequence of :class:`LineString` objects::
  446. >>> ls1 = LineString((0, 0), (1, 1))
  447. >>> ls2 = LineString((2, 2), (3, 3))
  448. >>> mls = MultiLineString(ls1, ls2)
  449. >>> mls = MultiLineString([ls1, ls2])
  450. .. attribute:: merged
  451. Returns a :class:`LineString` representing the line merge of
  452. all the components in this ``MultiLineString``.
  453. ``MultiPolygon``
  454. ----------------
  455. .. class:: MultiPolygon(*args, **kwargs)
  456. ``MultiPolygon`` objects may be instantiated by passing one or
  457. more :class:`Polygon` objects as arguments, or a single sequence
  458. of :class:`Polygon` objects::
  459. >>> p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
  460. >>> p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) )
  461. >>> mp = MultiPolygon(p1, p2)
  462. >>> mp = MultiPolygon([p1, p2])
  463. .. attribute:: cascaded_union
  464. Returns a :class:`Polygon` that is the union of all of the component
  465. polygons in this collection. The algorithm employed is significantly
  466. more efficient (faster) than trying to union the geometries together
  467. individually. [#fncascadedunion]_
  468. ``GeometryCollection``
  469. ----------------------
  470. .. class:: GeometryCollection(*args, **kwargs)
  471. ``GeometryCollection`` objects may be instantiated by passing in
  472. one or more other :class:`GEOSGeometry` as arguments, or a single
  473. sequence of :class:`GEOSGeometry` objects::
  474. >>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
  475. >>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
  476. >>> gc = GeometryCollection((Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly))
  477. .. _prepared-geometries:
  478. Prepared Geometries
  479. ===================
  480. In order to obtain a prepared geometry, just access the
  481. :attr:`GEOSGeometry.prepared` property. Once you have a
  482. ``PreparedGeometry`` instance its spatial predicate methods, listed below,
  483. may be used with other ``GEOSGeometry`` objects. An operation with a prepared
  484. geometry can be orders of magnitude faster -- the more complex the geometry
  485. that is prepared, the larger the speedup in the operation. For more information,
  486. please consult the `GEOS wiki page on prepared geometries <http://trac.osgeo.org/geos/wiki/PreparedGeometry>`_.
  487. For example::
  488. >>> from django.contrib.gis.geos import Point, Polygon
  489. >>> poly = Polygon.from_bbox((0, 0, 5, 5))
  490. >>> prep_poly = poly.prepared
  491. >>> prep_poly.contains(Point(2.5, 2.5))
  492. True
  493. ``PreparedGeometry``
  494. --------------------
  495. .. class:: PreparedGeometry
  496. All methods on ``PreparedGeometry`` take an ``other`` argument, which
  497. must be a :class:`GEOSGeometry` instance.
  498. .. method:: contains(other)
  499. .. method:: contains_properly(other)
  500. .. method:: covers(other)
  501. .. method:: crosses(other)
  502. .. versionadded:: 1.7
  503. .. note::
  504. GEOS 3.3 is *required* to use this predicate.
  505. .. method:: disjoint(other)
  506. .. versionadded:: 1.7
  507. .. note::
  508. GEOS 3.3 is *required* to use this predicate.
  509. .. method:: intersects(other)
  510. .. method:: overlaps(other)
  511. .. versionadded:: 1.7
  512. .. note::
  513. GEOS 3.3 is *required* to use this predicate.
  514. .. method:: touches(other)
  515. .. versionadded:: 1.7
  516. .. note::
  517. GEOS 3.3 is *required* to use this predicate.
  518. .. method:: within(other)
  519. .. versionadded:: 1.7
  520. .. note::
  521. GEOS 3.3 is *required* to use this predicate.
  522. Geometry Factories
  523. ==================
  524. .. function:: fromfile(file_h)
  525. :param file_h: input file that contains spatial data
  526. :type file_h: a Python ``file`` object or a string path to the file
  527. :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file
  528. Example::
  529. >>> from django.contrib.gis.geos import fromfile
  530. >>> g = fromfile('/home/bob/geom.wkt')
  531. .. function:: fromstr(string, [,srid=None])
  532. :param string: string that contains spatial data
  533. :type string: string
  534. :param srid: spatial reference identifier
  535. :type srid: int
  536. :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string
  537. Example::
  538. >>> from django.contrib.gis.geos import fromstr
  539. >>> pnt = fromstr('POINT(-90.5 29.5)', srid=4326)
  540. I/O Objects
  541. ===========
  542. Reader Objects
  543. --------------
  544. The reader I/O classes simply return a :class:`GEOSGeometry` instance from the
  545. WKB and/or WKT input given to their ``read(geom)`` method.
  546. .. class:: WKBReader
  547. Example::
  548. >>> from django.contrib.gis.geos import WKBReader
  549. >>> wkb_r = WKBReader()
  550. >>> wkb_r.read('0101000000000000000000F03F000000000000F03F')
  551. <Point object at 0x103a88910>
  552. .. class:: WKTReader
  553. Example::
  554. >>> from django.contrib.gis.geos import WKTReader
  555. >>> wkt_r = WKTReader()
  556. >>> wkt_r.read('POINT(1 1)')
  557. <Point object at 0x103a88b50>
  558. Writer Objects
  559. --------------
  560. All writer objects have a ``write(geom)`` method that returns either the
  561. WKB or WKT of the given geometry. In addition, :class:`WKBWriter` objects
  562. also have properties that may be used to change the byte order, and or
  563. include the SRID value (in other words, EWKB).
  564. .. class:: WKBWriter
  565. ``WKBWriter`` provides the most control over its output. By default it
  566. returns OGC-compliant WKB when its ``write`` method is called. However,
  567. it has properties that allow for the creation of EWKB, a superset of the
  568. WKB standard that includes additional information.
  569. .. method:: WKBWriter.write(geom)
  570. Returns the WKB of the given geometry as a Python ``buffer`` object.
  571. Example::
  572. >>> from django.contrib.gis.geos import Point, WKBWriter
  573. >>> pnt = Point(1, 1)
  574. >>> wkb_w = WKBWriter()
  575. >>> wkb_w.write(pnt)
  576. <read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930>
  577. .. method:: WKBWriter.write_hex(geom)
  578. Returns WKB of the geometry in hexadecimal. Example::
  579. >>> from django.contrib.gis.geos import Point, WKBWriter
  580. >>> pnt = Point(1, 1)
  581. >>> wkb_w = WKBWriter()
  582. >>> wkb_w.write_hex(pnt)
  583. '0101000000000000000000F03F000000000000F03F'
  584. .. attribute:: WKBWriter.byteorder
  585. This property may be set to change the byte-order of the geometry
  586. representation.
  587. =============== =================================================
  588. Byteorder Value Description
  589. =============== =================================================
  590. 0 Big Endian (e.g., compatible with RISC systems)
  591. 1 Little Endian (e.g., compatible with x86 systems)
  592. =============== =================================================
  593. Example::
  594. >>> from django.contrib.gis.geos import Point, WKBWriter
  595. >>> wkb_w = WKBWriter()
  596. >>> pnt = Point(1, 1)
  597. >>> wkb_w.write_hex(pnt)
  598. '0101000000000000000000F03F000000000000F03F'
  599. >>> wkb_w.byteorder = 0
  600. '00000000013FF00000000000003FF0000000000000'
  601. .. attribute:: WKBWriter.outdim
  602. This property may be set to change the output dimension of the geometry
  603. representation. In other words, if you have a 3D geometry then set to 3
  604. so that the Z value is included in the WKB.
  605. ============ ===========================
  606. Outdim Value Description
  607. ============ ===========================
  608. 2 The default, output 2D WKB.
  609. 3 Output 3D WKB.
  610. ============ ===========================
  611. Example::
  612. >>> from django.contrib.gis.geos import Point, WKBWriter
  613. >>> wkb_w = WKBWriter()
  614. >>> wkb_w.outdim
  615. 2
  616. >>> pnt = Point(1, 1, 1)
  617. >>> wkb_w.write_hex(pnt) # By default, no Z value included:
  618. '0101000000000000000000F03F000000000000F03F'
  619. >>> wkb_w.outdim = 3 # Tell writer to include Z values
  620. >>> wkb_w.write_hex(pnt)
  621. '0101000080000000000000F03F000000000000F03F000000000000F03F'
  622. .. attribute:: WKBWriter.srid
  623. Set this property with a boolean to indicate whether the SRID of the
  624. geometry should be included with the WKB representation. Example::
  625. >>> from django.contrib.gis.geos import Point, WKBWriter
  626. >>> wkb_w = WKBWriter()
  627. >>> pnt = Point(1, 1, srid=4326)
  628. >>> wkb_w.write_hex(pnt) # By default, no SRID included:
  629. '0101000000000000000000F03F000000000000F03F'
  630. >>> wkb_w.srid = True # Tell writer to include SRID
  631. >>> wkb_w.write_hex(pnt)
  632. '0101000020E6100000000000000000F03F000000000000F03F'
  633. .. class:: WKTWriter
  634. .. method:: WKTWriter.write(geom)
  635. Returns the WKT of the given geometry. Example::
  636. >>> from django.contrib.gis.geos import Point, WKTWriter
  637. >>> pnt = Point(1, 1)
  638. >>> wkt_w = WKTWriter()
  639. >>> wkt_w.write(pnt)
  640. 'POINT (1.0000000000000000 1.0000000000000000)'
  641. .. rubric:: Footnotes
  642. .. [#fnogc] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.net/docs/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.
  643. .. [#fncascadedunion] For more information, read Paul Ramsey's blog post about `(Much) Faster Unions in PostGIS 1.4 <http://blog.cleverelephant.ca/2009/01/must-faster-unions-in-postgis-14.html>`_ and Martin Davis' blog post on `Fast polygon merging in JTS using Cascaded Union <http://lin-ear-th-inking.blogspot.com/2007/11/fast-polygon-merging-in-jts-using.html>`_.
  644. Settings
  645. ========
  646. .. setting:: GEOS_LIBRARY_PATH
  647. GEOS_LIBRARY_PATH
  648. -----------------
  649. A string specifying the location of the GEOS C library. Typically,
  650. this setting is only used if the GEOS C library is in a non-standard
  651. location (e.g., ``/home/bob/lib/libgeos_c.so``).
  652. .. note::
  653. The setting must be the *full* path to the **C** shared library; in
  654. other words you want to use ``libgeos_c.so``, not ``libgeos.so``.
  655. Exceptions
  656. ==========
  657. .. exception:: GEOSException
  658. The base GEOS exception, indicates a GEOS-related error.