geos.txt 39 KB

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