geos.txt 39 KB

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