geos.txt 39 KB

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