geos.txt 37 KB

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