geos.txt 38 KB

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