geos.txt 39 KB

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