geos.txt 39 KB

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