geos.txt 36 KB

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