geos.txt 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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. __ https://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. All these constructors take the keyword argument ``srid``. For example::
  52. >>> from django.contrib.gis.geos import GEOSGeometry, LineString, Point
  53. >>> print(GEOSGeometry('POINT (0 0)', srid=4326))
  54. SRID=4326;POINT (0 0)
  55. >>> print(LineString((0, 0), (1, 1), srid=4326))
  56. SRID=4326;LINESTRING (0 0, 1 1)
  57. >>> print(Point(0, 0, srid=32140))
  58. SRID=32140;POINT (0 0)
  59. Finally, there is the :func:`fromfile` factory method which returns a
  60. :class:`GEOSGeometry` object from a file::
  61. >>> from django.contrib.gis.geos import fromfile
  62. >>> pnt = fromfile('/path/to/pnt.wkt')
  63. >>> pnt = fromfile(open('/path/to/pnt.wkt'))
  64. .. _geos-exceptions-in-logfile:
  65. .. admonition:: My logs are filled with GEOS-related errors
  66. You find many ``TypeError`` or ``AttributeError`` exceptions filling your
  67. Web server's log files. This generally means that you are creating GEOS
  68. objects at the top level of some of your Python modules. Then, due to a race
  69. condition in the garbage collector, your module is garbage collected before
  70. the GEOS object. To prevent this, create :class:`GEOSGeometry` objects
  71. inside the local scope of your functions/methods.
  72. Geometries are Pythonic
  73. -----------------------
  74. :class:`GEOSGeometry` objects are 'Pythonic', in other words components may
  75. be accessed, modified, and iterated over using standard Python conventions.
  76. For example, you can iterate over the coordinates in a :class:`Point`::
  77. >>> pnt = Point(5, 23)
  78. >>> [coord for coord in pnt]
  79. [5.0, 23.0]
  80. With any geometry object, the :attr:`GEOSGeometry.coords` property
  81. may be used to get the geometry coordinates as a Python tuple::
  82. >>> pnt.coords
  83. (5.0, 23.0)
  84. You can get/set geometry components using standard Python indexing
  85. techniques. However, what is returned depends on the geometry type
  86. of the object. For example, indexing on a :class:`LineString`
  87. returns a coordinate tuple::
  88. >>> from django.contrib.gis.geos import LineString
  89. >>> line = LineString((0, 0), (0, 50), (50, 50), (50, 0), (0, 0))
  90. >>> line[0]
  91. (0.0, 0.0)
  92. >>> line[-2]
  93. (50.0, 0.0)
  94. Whereas indexing on a :class:`Polygon` will return the ring
  95. (a :class:`LinearRing` object) corresponding to the index::
  96. >>> from django.contrib.gis.geos import Polygon
  97. >>> poly = Polygon( ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)) )
  98. >>> poly[0]
  99. <LinearRing object at 0x1044395b0>
  100. >>> poly[0][-2] # second-to-last coordinate of external ring
  101. (50.0, 0.0)
  102. In addition, coordinates/components of the geometry may added or modified,
  103. just like a Python list::
  104. >>> line[0] = (1.0, 1.0)
  105. >>> line.pop()
  106. (0.0, 0.0)
  107. >>> line.append((1.0, 1.0))
  108. >>> line.coords
  109. ((1.0, 1.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (1.0, 1.0))
  110. Geometries support set-like operators::
  111. >>> from django.contrib.gis.geos import LineString
  112. >>> ls1 = LineString((0, 0), (2, 2))
  113. >>> ls2 = LineString((1, 1), (3, 3))
  114. >>> print(ls1 | ls2) # equivalent to `ls1.union(ls2)`
  115. MULTILINESTRING ((0 0, 1 1), (1 1, 2 2), (2 2, 3 3))
  116. >>> print(ls1 & ls2) # equivalent to `ls1.intersection(ls2)`
  117. LINESTRING (1 1, 2 2)
  118. >>> print(ls1 - ls2) # equivalent to `ls1.difference(ls2)`
  119. LINESTRING(0 0, 1 1)
  120. >>> print(ls1 ^ ls2) # equivalent to `ls1.sym_difference(ls2)`
  121. MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))
  122. .. admonition:: Equality operator doesn't check spatial equality
  123. The :class:`~GEOSGeometry` equality operator uses
  124. :meth:`~GEOSGeometry.equals_exact`, not :meth:`~GEOSGeometry.equals`, i.e.
  125. it requires the compared geometries to have the same coordinates in the
  126. same positions::
  127. >>> from django.contrib.gis.geos import LineString
  128. >>> ls1 = LineString((0, 0), (1, 1))
  129. >>> ls2 = LineString((1, 1), (0, 0))
  130. >>> ls1.equals(ls2)
  131. True
  132. >>> ls1 == ls2
  133. False
  134. Geometry Objects
  135. ================
  136. ``GEOSGeometry``
  137. ----------------
  138. .. class:: GEOSGeometry(geo_input, srid=None)
  139. :param geo_input: Geometry input value (string or buffer)
  140. :param srid: spatial reference identifier
  141. :type srid: int
  142. This is the base class for all GEOS geometry objects. It initializes on the
  143. given ``geo_input`` argument, and then assumes the proper geometry subclass
  144. (e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object).
  145. The following input formats, along with their corresponding Python types,
  146. are accepted:
  147. ======================= ======================
  148. Format Input Type
  149. ======================= ======================
  150. WKT / EWKT ``str`` or ``unicode``
  151. HEX / HEXEWKB ``str`` or ``unicode``
  152. WKB / EWKB ``buffer``
  153. GeoJSON ``str`` or ``unicode``
  154. ======================= ======================
  155. Properties
  156. ~~~~~~~~~~
  157. .. attribute:: GEOSGeometry.coords
  158. Returns the coordinates of the geometry as a tuple.
  159. .. attribute:: GEOSGeometry.dims
  160. Returns the dimension of the geometry:
  161. * ``0`` for :class:`Point`\s and :class:`MultiPoint`\s
  162. * ``1`` for :class:`LineString`\s and :class:`MultiLineString`\s
  163. * ``2`` for :class:`Polygon`\s and :class:`MultiPolygon`\s
  164. * ``-1`` for empty :class:`GeometryCollection`\s
  165. * the maximum dimension of its elements for non-empty
  166. :class:`GeometryCollection`\s
  167. .. attribute:: GEOSGeometry.empty
  168. Returns whether or not the set of points in the geometry is empty.
  169. .. attribute:: GEOSGeometry.geom_type
  170. Returns a string corresponding to the type of geometry. For example::
  171. >>> pnt = GEOSGeometry('POINT(5 23)')
  172. >>> pnt.geom_type
  173. 'Point'
  174. .. attribute:: GEOSGeometry.geom_typeid
  175. Returns the GEOS geometry type identification number. The following table
  176. shows the value for each geometry type:
  177. =========================== ========
  178. Geometry ID
  179. =========================== ========
  180. :class:`Point` 0
  181. :class:`LineString` 1
  182. :class:`LinearRing` 2
  183. :class:`Polygon` 3
  184. :class:`MultiPoint` 4
  185. :class:`MultiLineString` 5
  186. :class:`MultiPolygon` 6
  187. :class:`GeometryCollection` 7
  188. =========================== ========
  189. .. attribute:: GEOSGeometry.num_coords
  190. Returns the number of coordinates in the geometry.
  191. .. attribute:: GEOSGeometry.num_geom
  192. Returns the number of geometries in this geometry. In other words, will
  193. return 1 on anything but geometry collections.
  194. .. attribute:: GEOSGeometry.hasz
  195. Returns a boolean indicating whether the geometry is three-dimensional.
  196. .. attribute:: GEOSGeometry.ring
  197. Returns a boolean indicating whether the geometry is a ``LinearRing``.
  198. .. attribute:: GEOSGeometry.simple
  199. Returns a boolean indicating whether the geometry is 'simple'. A geometry
  200. is simple if and only if it does not intersect itself (except at boundary
  201. points). For example, a :class:`LineString` object is not simple if it
  202. intersects itself. Thus, :class:`LinearRing` and :class:`Polygon` objects
  203. are always simple because they do cannot intersect themselves, by
  204. definition.
  205. .. attribute:: GEOSGeometry.valid
  206. Returns a boolean indicating whether the geometry is valid.
  207. .. attribute:: GEOSGeometry.valid_reason
  208. Returns a string describing the reason why a geometry is invalid.
  209. .. attribute:: GEOSGeometry.srid
  210. Property that may be used to retrieve or set the SRID associated with the
  211. geometry. For example::
  212. >>> pnt = Point(5, 23)
  213. >>> print(pnt.srid)
  214. None
  215. >>> pnt.srid = 4326
  216. >>> pnt.srid
  217. 4326
  218. Output Properties
  219. ~~~~~~~~~~~~~~~~~
  220. The properties in this section export the :class:`GEOSGeometry` object into
  221. a different. This output may be in the form of a string, buffer, or even
  222. another object.
  223. .. attribute:: GEOSGeometry.ewkt
  224. Returns the "extended" Well-Known Text of the geometry. This representation
  225. is specific to PostGIS and is a superset of the OGC WKT standard. [#fnogc]_
  226. Essentially the SRID is prepended to the WKT representation, for example
  227. ``SRID=4326;POINT(5 23)``.
  228. .. note::
  229. The output from this property does not include the 3dm, 3dz, and 4d
  230. information that PostGIS supports in its EWKT representations.
  231. .. attribute:: GEOSGeometry.hex
  232. Returns the WKB of this Geometry in hexadecimal form. Please note
  233. that the SRID value is not included in this representation
  234. because it is not a part of the OGC specification (use the
  235. :attr:`GEOSGeometry.hexewkb` property instead).
  236. .. attribute:: GEOSGeometry.hexewkb
  237. Returns the EWKB of this Geometry in hexadecimal form. This is an
  238. extension of the WKB specification that includes the SRID value
  239. that are a part of this geometry.
  240. .. attribute:: GEOSGeometry.json
  241. Returns the GeoJSON representation of the geometry. Note that the result is
  242. not a complete GeoJSON structure but only the ``geometry`` key content of a
  243. GeoJSON structure. See also :doc:`/ref/contrib/gis/serializers`.
  244. .. attribute:: GEOSGeometry.geojson
  245. Alias for :attr:`GEOSGeometry.json`.
  246. .. attribute:: GEOSGeometry.kml
  247. Returns a `KML`__ (Keyhole Markup Language) representation of the
  248. geometry. This should only be used for geometries with an SRID of
  249. 4326 (WGS84), but this restriction is not enforced.
  250. .. attribute:: GEOSGeometry.ogr
  251. Returns an :class:`~django.contrib.gis.gdal.OGRGeometry` object
  252. corresponding to the GEOS geometry.
  253. .. _wkb:
  254. .. attribute:: GEOSGeometry.wkb
  255. Returns the WKB (Well-Known Binary) representation of this Geometry
  256. as a Python buffer. SRID value is not included, use the
  257. :attr:`GEOSGeometry.ewkb` property instead.
  258. .. _ewkb:
  259. .. attribute:: GEOSGeometry.ewkb
  260. Return the EWKB representation of this Geometry as a Python buffer.
  261. This is an extension of the WKB specification that includes any SRID
  262. value that are a part of this geometry.
  263. .. attribute:: GEOSGeometry.wkt
  264. Returns the Well-Known Text of the geometry (an OGC standard).
  265. .. versionchanged:: 1.10
  266. Non-significant zeros are stripped from the output.
  267. __ https://developers.google.com/kml/documentation/
  268. Spatial Predicate Methods
  269. ~~~~~~~~~~~~~~~~~~~~~~~~~
  270. All of the following spatial predicate methods take another
  271. :class:`GEOSGeometry` instance (``other``) as a parameter, and
  272. return a boolean.
  273. .. method:: GEOSGeometry.contains(other)
  274. Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>` returns
  275. ``True``.
  276. .. method:: GEOSGeometry.covers(other)
  277. .. versionadded:: 1.10
  278. Returns ``True`` if this geometry covers the specified geometry.
  279. The ``covers`` predicate has the following equivalent definitions:
  280. * Every point of the other geometry is a point of this geometry.
  281. * The DE-9IM Intersection Matrix for the two geometries is
  282. ``T*****FF*``, ``*T****FF*``, ``***T**FF*``, or ``****T*FF*``.
  283. If either geometry is empty, returns ``False``.
  284. This predicate is similar to :meth:`GEOSGeometry.contains`, but is more
  285. inclusive (i.e. returns ``True`` for more cases). In particular, unlike
  286. :meth:`~GEOSGeometry.contains` it does not distinguish between points in the
  287. boundary and in the interior of geometries. For most situations,
  288. ``covers()`` should be preferred to :meth:`~GEOSGeometry.contains`. As an
  289. added benefit, ``covers()`` is more amenable to optimization and hence
  290. should outperform :meth:`~GEOSGeometry.contains`.
  291. .. method:: GEOSGeometry.crosses(other)
  292. Returns ``True`` if the DE-9IM intersection matrix for the two Geometries
  293. is ``T*T******`` (for a point and a curve,a point and an area or a line
  294. and an area) ``0********`` (for two curves).
  295. .. method:: GEOSGeometry.disjoint(other)
  296. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  297. is ``FF*FF****``.
  298. .. method:: GEOSGeometry.equals(other)
  299. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  300. is ``T*F**FFF*``.
  301. .. method:: GEOSGeometry.equals_exact(other, tolerance=0)
  302. Returns true if the two geometries are exactly equal, up to a
  303. specified tolerance. The ``tolerance`` value should be a floating
  304. point number representing the error tolerance in the comparison, e.g.,
  305. ``poly1.equals_exact(poly2, 0.001)`` will compare equality to within
  306. one thousandth of a unit.
  307. .. method:: GEOSGeometry.intersects(other)
  308. Returns ``True`` if :meth:`GEOSGeometry.disjoint` is ``False``.
  309. .. method:: GEOSGeometry.overlaps(other)
  310. Returns true if the DE-9IM intersection matrix for the two geometries
  311. is ``T*T***T**`` (for two points or two surfaces) ``1*T***T**``
  312. (for two curves).
  313. .. method:: GEOSGeometry.relate_pattern(other, pattern)
  314. Returns ``True`` if the elements in the DE-9IM intersection matrix
  315. for this geometry and the other matches the given ``pattern`` --
  316. a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
  317. .. method:: GEOSGeometry.touches(other)
  318. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  319. is ``FT*******``, ``F**T*****`` or ``F***T****``.
  320. .. method:: GEOSGeometry.within(other)
  321. Returns ``True`` if the DE-9IM intersection matrix for the two geometries
  322. is ``T*F**F***``.
  323. Topological Methods
  324. ~~~~~~~~~~~~~~~~~~~
  325. .. method:: GEOSGeometry.buffer(width, quadsegs=8)
  326. Returns a :class:`GEOSGeometry` that represents all points whose distance
  327. from this geometry is less than or equal to the given ``width``. The
  328. optional ``quadsegs`` keyword sets the number of segments used to
  329. approximate a quarter circle (defaults is 8).
  330. .. method:: GEOSGeometry.difference(other)
  331. Returns a :class:`GEOSGeometry` representing the points making up this
  332. geometry that do not make up other.
  333. .. method:: GEOSGeometry.interpolate(distance)
  334. .. method:: GEOSGeometry.interpolate_normalized(distance)
  335. Given a distance (float), returns the point (or closest point) within the
  336. geometry (:class:`LineString` or :class:`MultiLineString`) at that distance.
  337. The normalized version takes the distance as a float between 0 (origin) and
  338. 1 (endpoint).
  339. Reverse of :meth:`GEOSGeometry.project`.
  340. .. method:: GEOSGeometry.intersection(other)
  341. Returns a :class:`GEOSGeometry` representing the points shared by this
  342. geometry and other.
  343. .. method:: GEOSGeometry.project(point)
  344. .. method:: GEOSGeometry.project_normalized(point)
  345. Returns the distance (float) from the origin of the geometry
  346. (:class:`LineString` or :class:`MultiLineString`) to the point projected on
  347. the geometry (that is to a point of the line the closest to the given
  348. point). The normalized version returns the distance as a float between 0
  349. (origin) and 1 (endpoint).
  350. Reverse of :meth:`GEOSGeometry.interpolate`.
  351. .. method:: GEOSGeometry.relate(other)
  352. Returns the DE-9IM intersection matrix (a string) representing the
  353. topological relationship between this geometry and the other.
  354. .. method:: GEOSGeometry.simplify(tolerance=0.0, preserve_topology=False)
  355. Returns a new :class:`GEOSGeometry`, simplified to the specified tolerance
  356. using the Douglas-Peucker algorithm. A higher tolerance value implies
  357. fewer points in the output. If no tolerance is provided, it defaults to 0.
  358. By default, this function does not preserve topology. For example,
  359. :class:`Polygon` objects can be split, be collapsed into lines, or
  360. disappear. :class:`Polygon` holes can be created or disappear, and lines may
  361. cross. By specifying ``preserve_topology=True``, the result will have the
  362. same dimension and number of components as the input; this is significantly
  363. slower, however.
  364. .. method:: GEOSGeometry.sym_difference(other)
  365. Returns a :class:`GEOSGeometry` combining the points in this geometry
  366. not in other, and the points in other not in this geometry.
  367. .. method:: GEOSGeometry.union(other)
  368. Returns a :class:`GEOSGeometry` representing all the points in this
  369. geometry and the other.
  370. Topological Properties
  371. ~~~~~~~~~~~~~~~~~~~~~~
  372. .. attribute:: GEOSGeometry.boundary
  373. Returns the boundary as a newly allocated Geometry object.
  374. .. attribute:: GEOSGeometry.centroid
  375. Returns a :class:`Point` object representing the geometric center of
  376. the geometry. The point is not guaranteed to be on the interior
  377. of the geometry.
  378. .. attribute:: GEOSGeometry.convex_hull
  379. Returns the smallest :class:`Polygon` that contains all the points in
  380. the geometry.
  381. .. attribute:: GEOSGeometry.envelope
  382. Returns a :class:`Polygon` that represents the bounding envelope of
  383. this geometry. Note that it can also return a :class:`Point` if the input
  384. geometry is a point.
  385. .. attribute:: GEOSGeometry.point_on_surface
  386. Computes and returns a :class:`Point` guaranteed to be on the interior
  387. of this geometry.
  388. .. attribute:: GEOSGeometry.unary_union
  389. .. versionadded:: 1.10
  390. Computes the union of all the elements of this geometry.
  391. The result obeys the following contract:
  392. * Unioning a set of :class:`LineString`\s has the effect of fully noding and
  393. dissolving the linework.
  394. * Unioning a set of :class:`Polygon`\s will always return a :class:`Polygon`
  395. or :class:`MultiPolygon` geometry (unlike :meth:`GEOSGeometry.union`,
  396. which may return geometries of lower dimension if a topology collapse
  397. occurs).
  398. Other Properties & Methods
  399. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  400. .. attribute:: GEOSGeometry.area
  401. This property returns the area of the Geometry.
  402. .. attribute:: GEOSGeometry.extent
  403. This property returns the extent of this geometry as a 4-tuple,
  404. consisting of ``(xmin, ymin, xmax, ymax)``.
  405. .. method:: GEOSGeometry.clone()
  406. This method returns a :class:`GEOSGeometry` that is a clone of the original.
  407. .. method:: GEOSGeometry.distance(geom)
  408. Returns the distance between the closest points on this geometry and the
  409. given ``geom`` (another :class:`GEOSGeometry` object).
  410. .. note::
  411. GEOS distance calculations are linear -- in other words, GEOS does not
  412. perform a spherical calculation even if the SRID specifies a geographic
  413. coordinate system.
  414. .. attribute:: GEOSGeometry.length
  415. Returns the length of this geometry (e.g., 0 for a :class:`Point`,
  416. the length of a :class:`LineString`, or the circumference of
  417. a :class:`Polygon`).
  418. .. attribute:: GEOSGeometry.prepared
  419. Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.
  420. ``PreparedGeometry`` objects are optimized for the contains, intersects,
  421. covers, crosses, disjoint, overlaps, touches and within operations. Refer to
  422. the :ref:`prepared-geometries` documentation for more information.
  423. .. attribute:: GEOSGeometry.srs
  424. Returns a :class:`~django.contrib.gis.gdal.SpatialReference` object
  425. corresponding to the SRID of the geometry or ``None``.
  426. .. method:: GEOSGeometry.transform(ct, clone=False)
  427. Transforms the geometry according to the given coordinate transformation
  428. parameter (``ct``), which may be an integer SRID, spatial reference WKT
  429. string, a PROJ.4 string, a
  430. :class:`~django.contrib.gis.gdal.SpatialReference` object, or a
  431. :class:`~django.contrib.gis.gdal.CoordTransform` object. By default, the
  432. geometry is transformed in-place and nothing is returned. However if the
  433. ``clone`` keyword is set, then the geometry is not modified and a
  434. transformed clone of the geometry is returned instead.
  435. .. note::
  436. Raises :class:`~django.contrib.gis.geos.GEOSException` if GDAL is not
  437. available or if the geometry's SRID is ``None`` or less than 0. It
  438. doesn't impose any constraints on the geometry's SRID if called with a
  439. :class:`~django.contrib.gis.gdal.CoordTransform` object.
  440. .. versionchanged:: 1.10
  441. In previous versions, it required the geometry's SRID to be a
  442. positive integer even if it was called with a
  443. :class:`~django.contrib.gis.gdal.CoordTransform` object.
  444. ``Point``
  445. ---------
  446. .. class:: Point(x=None, y=None, z=None, srid=None)
  447. ``Point`` objects are instantiated using arguments that represent the
  448. component coordinates of the point or with a single sequence coordinates.
  449. For example, the following are equivalent::
  450. >>> pnt = Point(5, 23)
  451. >>> pnt = Point([5, 23])
  452. Empty ``Point`` objects may be instantiated by passing no arguments or an
  453. empty sequence. The following are equivalent::
  454. >>> pnt = Point()
  455. >>> pnt = Point([])
  456. .. versionchanged:: 1.10
  457. In previous versions, an empty ``Point`` couldn't be instantiated.
  458. ``LineString``
  459. --------------
  460. .. class:: LineString(*args, **kwargs)
  461. ``LineString`` objects are instantiated using arguments that are either a
  462. sequence of coordinates or :class:`Point` objects. For example, the
  463. following are equivalent::
  464. >>> ls = LineString((0, 0), (1, 1))
  465. >>> ls = LineString(Point(0, 0), Point(1, 1))
  466. In addition, ``LineString`` objects may also be created by passing in a
  467. single sequence of coordinate or :class:`Point` objects::
  468. >>> ls = LineString( ((0, 0), (1, 1)) )
  469. >>> ls = LineString( [Point(0, 0), Point(1, 1)] )
  470. Empty ``LineString`` objects may be instantiated by passing no arguments
  471. or an empty sequence. The following are equivalent::
  472. >>> ls = LineString()
  473. >>> ls = LineString([])
  474. .. versionchanged:: 1.10
  475. In previous versions, an empty ``LineString`` couldn't be instantiated.
  476. .. attribute:: closed
  477. .. versionadded:: 1.10
  478. Returns whether or not this ``LineString`` is closed.
  479. ``LinearRing``
  480. --------------
  481. .. class:: LinearRing(*args, **kwargs)
  482. ``LinearRing`` objects are constructed in the exact same way as
  483. :class:`LineString` objects, however the coordinates must be *closed*, in
  484. other words, the first coordinates must be the same as the last
  485. coordinates. For example::
  486. >>> ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))
  487. Notice that ``(0, 0)`` is the first and last coordinate -- if they were not
  488. equal, an error would be raised.
  489. ``Polygon``
  490. -----------
  491. .. class:: Polygon(*args, **kwargs)
  492. ``Polygon`` objects may be instantiated by passing in parameters that
  493. represent the rings of the polygon. The parameters must either be
  494. :class:`LinearRing` instances, or a sequence that may be used to construct a
  495. :class:`LinearRing`::
  496. >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
  497. >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))
  498. >>> poly = Polygon(ext_coords, int_coords)
  499. >>> poly = Polygon(LinearRing(ext_coords), LinearRing(int_coords))
  500. .. versionchanged:: 1.10
  501. In previous versions, an empty ``Polygon`` couldn't be instantiated.
  502. .. classmethod:: from_bbox(bbox)
  503. Returns a polygon object from the given bounding-box, a 4-tuple
  504. comprising ``(xmin, ymin, xmax, ymax)``.
  505. .. attribute:: num_interior_rings
  506. Returns the number of interior rings in this geometry.
  507. .. admonition:: Comparing Polygons
  508. Note that it is possible to compare ``Polygon`` objects directly with ``<``
  509. or ``>``, but as the comparison is made through Polygon's
  510. :class:`LineString`, it does not mean much (but is consistent and quick).
  511. You can always force the comparison with the :attr:`~GEOSGeometry.area`
  512. property::
  513. >>> if poly_1.area > poly_2.area:
  514. >>> pass
  515. Geometry Collections
  516. ====================
  517. ``MultiPoint``
  518. --------------
  519. .. class:: MultiPoint(*args, **kwargs)
  520. ``MultiPoint`` objects may be instantiated by passing in :class:`Point`
  521. objects as arguments, or a single sequence of :class:`Point` objects::
  522. >>> mp = MultiPoint(Point(0, 0), Point(1, 1))
  523. >>> mp = MultiPoint( (Point(0, 0), Point(1, 1)) )
  524. .. versionchanged:: 1.10
  525. In previous versions, an empty ``MultiPoint`` couldn't be instantiated.
  526. ``MultiLineString``
  527. -------------------
  528. .. class:: MultiLineString(*args, **kwargs)
  529. ``MultiLineString`` objects may be instantiated by passing in
  530. :class:`LineString` objects as arguments, or a single sequence of
  531. :class:`LineString` objects::
  532. >>> ls1 = LineString((0, 0), (1, 1))
  533. >>> ls2 = LineString((2, 2), (3, 3))
  534. >>> mls = MultiLineString(ls1, ls2)
  535. >>> mls = MultiLineString([ls1, ls2])
  536. .. versionchanged:: 1.10
  537. In previous versions, an empty ``MultiLineString`` couldn't be
  538. instantiated.
  539. .. attribute:: merged
  540. Returns a :class:`LineString` representing the line merge of
  541. all the components in this ``MultiLineString``.
  542. .. attribute:: closed
  543. .. versionadded:: 1.10
  544. Returns ``True`` if and only if all elements are closed. Requires GEOS 3.5.
  545. ``MultiPolygon``
  546. ----------------
  547. .. class:: MultiPolygon(*args, **kwargs)
  548. ``MultiPolygon`` objects may be instantiated by passing :class:`Polygon`
  549. objects as arguments, or a single sequence of :class:`Polygon` objects::
  550. >>> p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
  551. >>> p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) )
  552. >>> mp = MultiPolygon(p1, p2)
  553. >>> mp = MultiPolygon([p1, p2])
  554. .. versionchanged:: 1.10
  555. In previous versions, an empty ``MultiPolygon`` couldn't be
  556. instantiated.
  557. .. attribute:: cascaded_union
  558. .. deprecated:: 1.10
  559. Use the :attr:`GEOSGeometry.unary_union` property instead.
  560. Returns a :class:`Polygon` that is the union of all of the component
  561. polygons in this collection. The algorithm employed is significantly
  562. more efficient (faster) than trying to union the geometries together
  563. individually. [#fncascadedunion]_
  564. ``GeometryCollection``
  565. ----------------------
  566. .. class:: GeometryCollection(*args, **kwargs)
  567. ``GeometryCollection`` objects may be instantiated by passing in other
  568. :class:`GEOSGeometry` as arguments, or a single sequence of
  569. :class:`GEOSGeometry` objects::
  570. >>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
  571. >>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
  572. >>> gc = GeometryCollection((Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly))
  573. .. versionchanged:: 1.10
  574. In previous versions, an empty ``GeometryCollection`` couldn't be
  575. instantiated.
  576. .. _prepared-geometries:
  577. Prepared Geometries
  578. ===================
  579. In order to obtain a prepared geometry, just access the
  580. :attr:`GEOSGeometry.prepared` property. Once you have a
  581. ``PreparedGeometry`` instance its spatial predicate methods, listed below,
  582. may be used with other ``GEOSGeometry`` objects. An operation with a prepared
  583. geometry can be orders of magnitude faster -- the more complex the geometry
  584. that is prepared, the larger the speedup in the operation. For more information,
  585. please consult the `GEOS wiki page on prepared geometries <https://trac.osgeo.org/geos/wiki/PreparedGeometry>`_.
  586. For example::
  587. >>> from django.contrib.gis.geos import Point, Polygon
  588. >>> poly = Polygon.from_bbox((0, 0, 5, 5))
  589. >>> prep_poly = poly.prepared
  590. >>> prep_poly.contains(Point(2.5, 2.5))
  591. True
  592. ``PreparedGeometry``
  593. --------------------
  594. .. class:: PreparedGeometry
  595. All methods on ``PreparedGeometry`` take an ``other`` argument, which
  596. must be a :class:`GEOSGeometry` instance.
  597. .. method:: contains(other)
  598. .. method:: contains_properly(other)
  599. .. method:: covers(other)
  600. .. method:: crosses(other)
  601. .. method:: disjoint(other)
  602. .. method:: intersects(other)
  603. .. method:: overlaps(other)
  604. .. method:: touches(other)
  605. .. method:: within(other)
  606. Geometry Factories
  607. ==================
  608. .. function:: fromfile(file_h)
  609. :param file_h: input file that contains spatial data
  610. :type file_h: a Python ``file`` object or a string path to the file
  611. :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file
  612. Example::
  613. >>> from django.contrib.gis.geos import fromfile
  614. >>> g = fromfile('/home/bob/geom.wkt')
  615. .. function:: fromstr(string, srid=None)
  616. :param string: string that contains spatial data
  617. :type string: string
  618. :param srid: spatial reference identifier
  619. :type srid: int
  620. :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string
  621. ``fromstr(string, srid)`` is equivalent to
  622. :class:`GEOSGeometry(string, srid) <GEOSGeometry>`.
  623. Example::
  624. >>> from django.contrib.gis.geos import fromstr
  625. >>> pnt = fromstr('POINT(-90.5 29.5)', srid=4326)
  626. I/O Objects
  627. ===========
  628. Reader Objects
  629. --------------
  630. The reader I/O classes simply return a :class:`GEOSGeometry` instance from the
  631. WKB and/or WKT input given to their ``read(geom)`` method.
  632. .. class:: WKBReader
  633. Example::
  634. >>> from django.contrib.gis.geos import WKBReader
  635. >>> wkb_r = WKBReader()
  636. >>> wkb_r.read('0101000000000000000000F03F000000000000F03F')
  637. <Point object at 0x103a88910>
  638. .. class:: WKTReader
  639. Example::
  640. >>> from django.contrib.gis.geos import WKTReader
  641. >>> wkt_r = WKTReader()
  642. >>> wkt_r.read('POINT(1 1)')
  643. <Point object at 0x103a88b50>
  644. Writer Objects
  645. --------------
  646. All writer objects have a ``write(geom)`` method that returns either the
  647. WKB or WKT of the given geometry. In addition, :class:`WKBWriter` objects
  648. also have properties that may be used to change the byte order, and or
  649. include the SRID value (in other words, EWKB).
  650. .. class:: WKBWriter(dim=2)
  651. ``WKBWriter`` provides the most control over its output. By default it
  652. returns OGC-compliant WKB when its ``write`` method is called. However,
  653. it has properties that allow for the creation of EWKB, a superset of the
  654. WKB standard that includes additional information. See the
  655. :attr:`WKBWriter.outdim` documentation for more details about the ``dim``
  656. argument.
  657. .. versionchanged:: 1.10
  658. The ability to pass the ``dim`` argument to the constructor was added.
  659. .. method:: WKBWriter.write(geom)
  660. Returns the WKB of the given geometry as a Python ``buffer`` object.
  661. Example::
  662. >>> from django.contrib.gis.geos import Point, WKBWriter
  663. >>> pnt = Point(1, 1)
  664. >>> wkb_w = WKBWriter()
  665. >>> wkb_w.write(pnt)
  666. <read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930>
  667. .. method:: WKBWriter.write_hex(geom)
  668. Returns WKB of the geometry in hexadecimal. Example::
  669. >>> from django.contrib.gis.geos import Point, WKBWriter
  670. >>> pnt = Point(1, 1)
  671. >>> wkb_w = WKBWriter()
  672. >>> wkb_w.write_hex(pnt)
  673. '0101000000000000000000F03F000000000000F03F'
  674. .. attribute:: WKBWriter.byteorder
  675. This property may be set to change the byte-order of the geometry
  676. representation.
  677. =============== =================================================
  678. Byteorder Value Description
  679. =============== =================================================
  680. 0 Big Endian (e.g., compatible with RISC systems)
  681. 1 Little Endian (e.g., compatible with x86 systems)
  682. =============== =================================================
  683. Example::
  684. >>> from django.contrib.gis.geos import Point, WKBWriter
  685. >>> wkb_w = WKBWriter()
  686. >>> pnt = Point(1, 1)
  687. >>> wkb_w.write_hex(pnt)
  688. '0101000000000000000000F03F000000000000F03F'
  689. >>> wkb_w.byteorder = 0
  690. '00000000013FF00000000000003FF0000000000000'
  691. .. attribute:: WKBWriter.outdim
  692. This property may be set to change the output dimension of the geometry
  693. representation. In other words, if you have a 3D geometry then set to 3
  694. so that the Z value is included in the WKB.
  695. ============ ===========================
  696. Outdim Value Description
  697. ============ ===========================
  698. 2 The default, output 2D WKB.
  699. 3 Output 3D WKB.
  700. ============ ===========================
  701. Example::
  702. >>> from django.contrib.gis.geos import Point, WKBWriter
  703. >>> wkb_w = WKBWriter()
  704. >>> wkb_w.outdim
  705. 2
  706. >>> pnt = Point(1, 1, 1)
  707. >>> wkb_w.write_hex(pnt) # By default, no Z value included:
  708. '0101000000000000000000F03F000000000000F03F'
  709. >>> wkb_w.outdim = 3 # Tell writer to include Z values
  710. >>> wkb_w.write_hex(pnt)
  711. '0101000080000000000000F03F000000000000F03F000000000000F03F'
  712. .. attribute:: WKBWriter.srid
  713. Set this property with a boolean to indicate whether the SRID of the
  714. geometry should be included with the WKB representation. Example::
  715. >>> from django.contrib.gis.geos import Point, WKBWriter
  716. >>> wkb_w = WKBWriter()
  717. >>> pnt = Point(1, 1, srid=4326)
  718. >>> wkb_w.write_hex(pnt) # By default, no SRID included:
  719. '0101000000000000000000F03F000000000000F03F'
  720. >>> wkb_w.srid = True # Tell writer to include SRID
  721. >>> wkb_w.write_hex(pnt)
  722. '0101000020E6100000000000000000F03F000000000000F03F'
  723. .. class:: WKTWriter(dim=2, trim=False, precision=None)
  724. This class allows outputting the WKT representation of a geometry. See the
  725. :attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes for
  726. details about the constructor arguments.
  727. .. versionchanged:: 1.10
  728. The ability to pass the ``dim``, ``trim``, and ``precision`` arguments
  729. to the constructor was added.
  730. .. method:: WKTWriter.write(geom)
  731. Returns the WKT of the given geometry. Example::
  732. >>> from django.contrib.gis.geos import Point, WKTWriter
  733. >>> pnt = Point(1, 1)
  734. >>> wkt_w = WKTWriter()
  735. >>> wkt_w.write(pnt)
  736. 'POINT (1.0000000000000000 1.0000000000000000)'
  737. .. attribute:: WKTWriter.outdim
  738. See :attr:`WKBWriter.outdim`.
  739. .. attribute:: WKTWriter.trim
  740. .. versionadded:: 1.10
  741. This property is used to enable or disable trimming of
  742. unnecessary decimals.
  743. >>> from django.contrib.gis.geos import Point, WKTWriter
  744. >>> pnt = Point(1, 1)
  745. >>> wkt_w = WKTWriter()
  746. >>> wkt_w.trim
  747. False
  748. >>> wkt_w.write(pnt)
  749. 'POINT (1.0000000000000000 1.0000000000000000)'
  750. >>> wkt_w.trim = True
  751. >>> wkt_w.write(pnt)
  752. 'POINT (1 1)'
  753. .. attribute:: WKTWriter.precision
  754. .. versionadded:: 1.10
  755. This property controls the rounding precision of coordinates;
  756. if set to ``None`` rounding is disabled.
  757. >>> from django.contrib.gis.geos import Point, WKTWriter
  758. >>> pnt = Point(1.44, 1.66)
  759. >>> wkt_w = WKTWriter()
  760. >>> print(wkt_w.precision)
  761. None
  762. >>> wkt_w.write(pnt)
  763. 'POINT (1.4399999999999999 1.6599999999999999)'
  764. >>> wkt_w.precision = 0
  765. >>> wkt_w.write(pnt)
  766. 'POINT (1 2)'
  767. >>> wkt_w.precision = 1
  768. >>> wkt_w.write(pnt)
  769. 'POINT (1.4 1.7)'
  770. .. rubric:: Footnotes
  771. .. [#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.
  772. .. [#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>`_.
  773. Settings
  774. ========
  775. .. setting:: GEOS_LIBRARY_PATH
  776. ``GEOS_LIBRARY_PATH``
  777. ---------------------
  778. A string specifying the location of the GEOS C library. Typically,
  779. this setting is only used if the GEOS C library is in a non-standard
  780. location (e.g., ``/home/bob/lib/libgeos_c.so``).
  781. .. note::
  782. The setting must be the *full* path to the **C** shared library; in
  783. other words you want to use ``libgeos_c.so``, not ``libgeos.so``.
  784. Exceptions
  785. ==========
  786. .. exception:: GEOSException
  787. The base GEOS exception, indicates a GEOS-related error.