PageRenderTime 110ms CodeModel.GetById 96ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 5ms

/docs/ref/contrib/gis/geos.txt

https://code.google.com/p/mango-py/
Plain Text | 917 lines | 623 code | 294 blank | 0 comment | 0 complexity | da9695c721f9f1d73d55b327a4984f35 MD5 | raw file
  1.. _ref-geos:
  2
  3========
  4GEOS API
  5========
  6
  7.. module:: django.contrib.gis.geos
  8   :synopsis: GeoDjango's high-level interface to the GEOS library.
  9
 10Background
 11==========
 12
 13What is GEOS?
 14-------------
 15
 16`GEOS`__ stands for **G**\ eometry **E**\ ngine - **O**\ pen **S**\ ource,
 17and is a C++ library, ported from the  `Java Topology Suite`__.  GEOS
 18implements the OpenGIS `Simple Features for SQL`__ spatial predicate functions
 19and spatial operators. GEOS, now an OSGeo project, was initially developed and
 20maintained by `Refractions Research`__ of Victoria, Canada.
 21
 22__ http://trac.osgeo.org/geos/
 23__ http://sourceforge.net/projects/jts-topo-suite/
 24__ http://www.opengeospatial.org/standards/sfs
 25__ http://www.refractions.net/
 26
 27Features
 28--------
 29
 30GeoDjango implements a high-level Python wrapper for the GEOS library, its
 31features include:
 32
 33* A BSD-licensed interface to the GEOS geometry routines, implemented purely
 34  in Python using ``ctypes``.
 35* Loosely-coupled to GeoDjango.  For example, :class:`GEOSGeometry` objects
 36  may be used outside of a django project/application.  In other words,
 37  no need to have ``DJANGO_SETTINGS_MODULE`` set or use a database, etc.
 38* Mutability: :class:`GEOSGeometry` objects may be modified.
 39* Cross-platform and tested; compatible with Windows, Linux, Solaris, and Mac
 40  OS X platforms.
 41
 42.. _geos-tutorial:
 43
 44Tutorial
 45========
 46
 47This section contains a brief introduction and tutorial to using
 48:class:`GEOSGeometry` objects.
 49
 50Creating a Geometry
 51-------------------
 52
 53:class:`GEOSGeometry` objects may be created in a few ways.  The first is
 54to simply instantiate the object on some spatial input -- the following
 55are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON::
 56
 57    >>> from django.contrib.gis.geos import GEOSGeometry
 58    >>> pnt = GEOSGeometry('POINT(5 23)') # WKT
 59    >>> pnt = GEOSGeometry('010100000000000000000014400000000000003740') # HEX
 60    >>> pnt = GEOSGeometry(buffer('\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x007@'))
 61    >>> pnt = GEOSGeometry('{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }') # GeoJSON
 62
 63Another option is to use the constructor for the specific geometry type
 64that you wish to create.  For example, a :class:`Point` object may be
 65created by passing in the X and Y coordinates into its constructor::
 66
 67    >>> from django.contrib.gis.geos import Point
 68    >>> pnt = Point(5, 23)
 69
 70Finally, there are :func:`fromstr` and :func:`fromfile` factory methods, which
 71return a :class:`GEOSGeometry` object from an input string or a file::
 72
 73    >>> from django.contrib.gis.geos import fromstr, fromfile
 74    >>> pnt = fromstr('POINT(5 23)')
 75    >>> pnt = fromfile('/path/to/pnt.wkt')
 76    >>> pnt = fromfile(open('/path/to/pnt.wkt'))
 77
 78Geometries are Pythonic
 79-----------------------
 80:class:`GEOSGeometry` objects are 'Pythonic', in other words components may
 81be accessed, modified, and iterated over using standard Python conventions.
 82For example, you can iterate over the coordinates in a :class:`Point`::
 83
 84    >>> pnt = Point(5, 23)
 85    >>> [coord for coord in pnt]
 86    [5.0, 23.0]
 87
 88With any geometry object, the :attr:`GEOSGeometry.coords` property
 89may be used to get the geometry coordinates as a Python tuple::
 90
 91    >>> pnt.coords
 92    (5.0, 23.0)
 93
 94You can get/set geometry components using standard Python indexing
 95techniques.  However, what is returned depends on the geometry type
 96of the object.  For example, indexing on a :class:`LineString`
 97returns a coordinate tuple::
 98
 99    >>> from django.contrib.gis.geos import LineString
100    >>> line = LineString((0, 0), (0, 50), (50, 50), (50, 0), (0, 0))
101    >>> line[0]
102    (0.0, 0.0)
103    >>> line[-2]
104    (50.0, 0.0)
105
106Whereas indexing on a :class:`Polygon` will return the ring
107(a :class:`LinearRing` object) corresponding to the index::
108
109    >>> from django.contrib.gis.geos import Polygon
110    >>> poly = Polygon( ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)) )
111    >>> poly[0]
112    <LinearRing object at 0x1044395b0>
113    >>> poly[0][-2] # second-to-last coordinate of external ring
114    (50.0, 0.0)
115
116In addition, coordinates/components of the geometry may added or modified,
117just like a Python list::
118
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
126Geometry Objects
127================
128
129``GEOSGeometry``
130----------------
131
132.. class:: GEOSGeometry(geo_input[, srid=None])
133
134  :param geo_input: Geometry input value
135  :type geo_input: string or buffer
136  :param srid: spatial reference identifier
137  :type srid: integer
138
139This is the base class for all GEOS geometry objects.  It initializes on the
140given ``geo_input`` argument, and then assumes the proper geometry subclass
141(e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object).
142
143The following input formats, along with their corresponding Python types,
144are accepted:
145
146=============  ======================
147Format         Input Type
148=============  ======================
149WKT / EWKT     ``str`` or ``unicode``
150HEX / HEXEWKB  ``str`` or ``unicode``
151WKB / EWKB     ``buffer``
152GeoJSON        ``str`` or ``unicode``
153=============  ======================
154
155Properties
156~~~~~~~~~~
157
158.. attribute:: GEOSGeometry.coords
159
160Returns the coordinates of the geometry as a tuple.
161
162.. attribute:: GEOSGeometry.empty
163
164Returns whether or not the set of points in the geometry is empty.
165
166.. attribute:: GEOSGeometry.geom_type
167
168Returns a string corresponding to the type of geometry.  For example::
169
170    >>> pnt = GEOSGeometry('POINT(5 23)')
171    >>> pnt.geom_type
172    'Point'
173
174.. attribute:: GEOSGeometry.geom_typeid
175
176Returns the GEOS geometry type identification number.  The following table
177shows the value for each geometry type:
178
179===========================  ========
180Geometry                     ID
181===========================  ========
182:class:`Point`               0
183:class:`LineString`          1
184:class:`LinearRing`          2
185:class:`Polygon`             3
186:class:`MultiPoint`          4
187:class:`MultiLineString`     5
188:class:`MultiPolygon`        6
189:class:`GeometryCollection`  7
190===========================  ========
191
192.. attribute:: GEOSGeometry.num_coords
193
194Returns the number of coordinates in the geometry.
195
196.. attribute:: GEOSGeometry.num_geom
197
198Returns the number of geometries in this geometry.  In other words, will
199return 1 on anything but geometry collections.
200
201.. attribute:: GEOSGeometry.hasz
202
203Returns a boolean indicating whether the geometry is three-dimensional.
204
205.. attribute:: GEOSGeometry.ring
206
207Returns a boolean indicating whether the geometry is a ``LinearRing``.
208
209.. attribute:: GEOSGeometry.simple
210
211Returns a boolean indicating whether the geometry is 'simple'. A geometry
212is simple if and only if it does not intersect itself (except at boundary
213points).  For example, a :class:`LineString` object is not simple if it
214intersects itself. Thus, :class:`LinearRing` and :class`Polygon` objects
215are always simple because they do cannot intersect themselves, by
216definition.
217
218.. attribute:: GEOSGeometry.valid
219
220Returns a boolean indicating whether the geometry is valid.
221
222.. attribute:: GEOSGeometry.valid_reason
223
224.. versionadded:: 1.3
225
226Returns a string describing the reason why a geometry is invalid.
227
228.. attribute:: GEOSGeometry.srid
229
230Property that may be used to retrieve or set the SRID associated with the
231geometry.  For example::
232
233    >>> pnt = Point(5, 23)
234    >>> print pnt.srid
235    None
236    >>> pnt.srid = 4326
237    >>> pnt.srid
238    4326
239
240Output Properties
241~~~~~~~~~~~~~~~~~
242
243The properties in this section export the :class:`GEOSGeometry` object into
244a different.  This output may be in the form of a string, buffer, or even
245another object.
246
247.. attribute:: GEOSGeometry.ewkt
248
249Returns the "extended" Well-Known Text of the geometry.  This representation
250is specific to PostGIS and is a super set of the OGC WKT standard. [#fnogc]_
251Essentially the SRID is prepended to the WKT representation, for example
252``SRID=4326;POINT(5 23)``.
253
254.. note::
255
256   The output from this property does not include the 3dm, 3dz, and 4d
257   information that PostGIS supports in its EWKT representations.
258
259.. attribute:: GEOSGeometry.hex
260
261Returns the WKB of this Geometry in hexadecimal form.  Please note
262that the SRID and Z values are not included in this representation
263because it is not a part of the OGC specification (use the
264:attr:`GEOSGeometry.hexewkb` property instead).
265
266.. attribute:: GEOSGeometry.hexewkb
267
268.. versionadded:: 1.2
269
270Returns the EWKB of this Geometry in hexadecimal form.  This is an
271extension of the WKB specification that includes SRID and Z values
272that are a part of this geometry.
273
274.. note::
275
276   GEOS 3.1 is *required* if you want valid 3D HEXEWKB.
277
278.. attribute:: GEOSGeometry.json
279
280Returns the GeoJSON representation of the geometry.
281
282.. note::
283
284    Requires GDAL.
285
286.. attribute:: GEOSGeometry.geojson
287
288Alias for :attr:`GEOSGeometry.json`.
289
290.. attribute:: GEOSGeometry.kml
291
292Returns a `KML`__ (Keyhole Markup Language) representation of the
293geometry.  This should only be used for geometries with an SRID of
2944326 (WGS84), but this restriction is not enforced.
295
296.. attribute:: GEOSGeometry.ogr
297
298Returns an :class:`~django.contrib.gis.gdal.OGRGeometry` object
299correspondg to the GEOS geometry.
300
301.. note::
302
303    Requires GDAL.
304
305.. _wkb:
306
307.. attribute:: GEOSGeometry.wkb
308
309Returns the WKB (Well-Known Binary) representation of this Geometry
310as a Python buffer.  SRID and Z values are not included, use the
311:attr:`GEOSGeometry.ewkb` property instead.
312
313.. _ewkb:
314
315.. attribute:: GEOSGeometry.ewkb
316
317.. versionadded:: 1.2
318
319Return the EWKB representation of this Geometry as a Python buffer.
320This is an extension of the WKB specification that includes any SRID
321and Z values that are a part of this geometry.
322
323.. note::
324
325   GEOS 3.1 is *required* if you want valid 3D EWKB.
326
327.. attribute:: GEOSGeometry.wkt
328
329Returns the Well-Known Text of the geometry (an OGC standard).
330
331__ http://code.google.com/apis/kml/documentation/
332
333Spatial Predicate Methods
334~~~~~~~~~~~~~~~~~~~~~~~~~
335
336All of the following spatial predicate methods take another
337:class:`GEOSGeometry` instance (``other``) as a parameter, and
338return a boolean.
339
340.. method:: GEOSGeometry.contains(other)
341
342Returns ``True`` if :meth:`GEOSGeometry.within` is ``False``.
343
344.. method:: GEOSGeometry.crosses(other)
345
346Returns ``True`` if the DE-9IM intersection matrix for the two Geometries
347is ``T*T******`` (for a point and a curve,a point and an area or a line
348and an area) ``0********`` (for two curves).
349
350.. method:: GEOSGeometry.disjoint(other)
351
352Returns ``True`` if the DE-9IM intersection matrix for the two geometries
353is ``FF*FF****``.
354
355.. method:: GEOSGeometry.equals(other)
356
357Returns ``True`` if the DE-9IM intersection matrix for the two geometries
358is ``T*F**FFF*``.
359
360.. method:: GEOSGeometry.equals_exact(other, tolerance=0)
361
362Returns true if the two geometries are exactly equal, up to a
363specified tolerance.  The ``tolerance`` value should be a floating
364point number representing the error tolerance in the comparison, e.g.,
365``poly1.equals_exact(poly2, 0.001)`` will compare equality to within
366one thousandth of a unit.
367
368.. method:: GEOSGeometry.intersects(other)
369
370Returns ``True`` if :meth:`GEOSGeometry.disjoint` is ``False``.
371
372.. method:: GEOSGeometry.overlaps(other)
373
374Returns true if the DE-9IM intersection matrix for the two geometries
375is ``T*T***T**`` (for two points or two surfaces) ``1*T***T**``
376(for two curves).
377
378.. method:: GEOSGeometry.relate_pattern(other, pattern)
379
380Returns ``True`` if the elements in the DE-9IM intersection matrix
381for this geometry and the other matches the given ``pattern`` --
382a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.
383
384.. method:: GEOSGeometry.touches(other)
385
386Returns ``True`` if the DE-9IM intersection matrix for the two geometries
387is ``FT*******``, ``F**T*****`` or ``F***T****``.
388
389.. method:: GEOSGeometry.within(other)
390
391Returns ``True`` if the DE-9IM intersection matrix for the two geometries
392is ``T*F**F***``.
393
394Topological Methods
395~~~~~~~~~~~~~~~~~~~
396
397.. method:: GEOSGeometry.buffer(width, quadsegs=8)
398
399Returns a :class:`GEOSGeometry` that represents all points whose distance
400from this geometry is less than or equal to the given ``width``. The optional
401``quadsegs`` keyword sets the number of segments used to approximate a
402quarter circle (defaults is 8).
403
404.. method:: GEOSGeometry.difference(other)
405
406Returns a :class:`GEOSGeometry` representing the points making up this
407geometry that do not make up other.
408
409.. method:: GEOSGeometry:intersection(other)
410
411Returns a :class:`GEOSGeometry` representing the points shared by this
412geometry and other.
413
414.. method:: GEOSGeometry.relate(other)
415
416Returns the DE-9IM intersection matrix (a string) representing the
417topological relationship between this geometry and the other.
418
419.. method:: GEOSGeometry.simplify(tolerance=0.0, preserve_topology=False)
420
421Returns a new :class:`GEOSGeometry`, simplified using the Douglas-Peucker
422algorithm to the specified tolerance.  A higher tolerance value implies
423less points in the output.  If no tolerance is tolerance provided,
424it defaults to 0.
425
426By default, this function does not preserve topology - e.g.,
427:class:`Polygon` objects can be split, collapsed into lines or disappear.
428:class:`Polygon` holes can be created or disappear, and lines can cross.
429By specifying ``preserve_topology=True``, the result will have the same
430dimension and number of components as the input, however, this is
431significantly slower.
432
433.. method:: GEOSGeometry.sym_difference(other)
434
435Returns a :class:`GEOSGeometry` combining the points in this geometry
436not in other, and the points in other not in this geometry.
437
438.. method:: GEOSGeometry.union(other)
439
440Returns a :class:`GEOSGeometry` representing all the points in this
441geometry and the other.
442
443Topological Properties
444~~~~~~~~~~~~~~~~~~~~~~
445
446.. attribute:: GEOSGeometry.boundary
447
448Returns the boundary as a newly allocated Geometry object.
449
450.. attribute:: GEOSGeometry.centroid
451
452Returns a :class:`Point` object representing the geometric center of
453the geometry.  The point is not guaranteed to be on the interior
454of the geometry.
455
456.. attribute:: GEOSGeometry.convex_hull
457
458Returns the smallest :class:`Polygon` that contains all the points in
459the geometry.
460
461.. attribute:: GEOSGeometry.envelope
462
463Returns a :class:`Polygon` that represents the bounding envelope of
464this geometry.
465
466.. attribute:: GEOSGeometry.point_on_surface
467
468Computes and returns a :class:`Point` guaranteed to be on the interior
469of this geometry.
470
471Other Properties & Methods
472~~~~~~~~~~~~~~~~~~~~~~~~~~
473
474.. attribute:: GEOSGeometry.area
475
476This property returns the area of the Geometry.
477
478.. attribute:: GEOSGeometry.extent
479
480This property returns the extent of this geometry as a 4-tuple,
481consisting of (xmin, ymin, xmax, ymax).
482
483.. method:: GEOSGeometry.clone()
484
485This method returns a :class:`GEOSGeometry` that is a clone of the original.
486
487.. method:: GEOSGeometry.distance(geom)
488
489Returns the distance between the closest points on this geometry and the given
490``geom`` (another :class:`GEOSGeometry` object).
491
492.. note::
493
494    GEOS distance calculations are  linear -- in other words, GEOS does not
495    perform a spherical calculation even if the SRID specifies a geographic
496    coordinate system.
497
498.. attribute:: GEOSGeometry.length
499
500Returns the length of this geometry (e.g., 0 for a :class:`Point`,
501the length of a :class:`LineString`, or the circumference of
502a :class:`Polygon`).
503
504.. attribute:: GEOSGeometry.prepared
505
506.. note::
507
508    Support for prepared geometries requires GEOS 3.1.
509
510Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.
511``PreparedGeometry`` objects are optimized for the contains, intersects,
512and covers operations.  Refer to the :ref:`prepared-geometries` documentation
513for more information.
514
515.. attribute:: GEOSGeometry.srs
516
517Returns a :class:`~django.contrib.gis.gdal.SpatialReference` object
518corresponding to the SRID of the geometry or ``None``.
519
520.. note::
521
522    Requires GDAL.
523
524.. method:: GEOSGeometry.transform(ct, clone=False)
525
526.. versionchanged:: 1.3
527
528Transforms the geometry according to the given coordinate transformation paramter
529(``ct``), which may be an integer SRID, spatial reference WKT string,
530a PROJ.4 string, a :class:`~django.contrib.gis.gdal.SpatialReference` object, or a
531:class:`~django.contrib.gis.gdal.CoordTransform` object. By default, the geometry
532is transformed in-place and nothing is returned. However if the ``clone`` keyword
533is set, then the geometry is not modified and a transformed clone of the geometry
534is returned instead.
535
536.. note::
537
538    Requires GDAL.
539
540.. note::
541
542   Prior to 1.3, this method would silently no-op if GDAL was not available.
543   Now, a :class:`~django.contrib.gis.geos.GEOSException` is raised as
544   application code relying on this behavior is in error. In addition,
545   use of this method when the SRID is ``None`` or less than 0 now generates
546   a warning because a :class:`~django.contrib.gis.geos.GEOSException` will
547   be raised instead in version 1.5.
548
549
550``Point``
551---------
552
553.. class:: Point(x, y, z=None, srid=None)
554
555   ``Point`` objects are instantiated using arguments that represent
556   the component coordinates of the point or with a single sequence
557   coordinates.  For example, the following are equivalent::
558
559       >>> pnt = Point(5, 23)
560       >>> pnt = Point([5, 23])
561
562``LineString``
563--------------
564
565.. class:: LineString(*args, **kwargs)
566
567   ``LineString`` objects are instantiated using arguments that are
568   either a sequence of coordinates or :class:`Point` objects.
569   For example, the following are equivalent::
570
571       >>> ls = LineString((0, 0), (1, 1))
572       >>> ls = LineString(Point(0, 0), Point(1, 1))
573
574   In addition, ``LineString`` objects may also be created by passing
575   in a single sequence of coordinate or :class:`Point` objects::
576
577       >>> ls = LineString( ((0, 0), (1, 1)) )
578       >>> ls = LineString( [Point(0, 0), Point(1, 1)] )
579
580``LinearRing``
581--------------
582
583.. class:: LinearRing(*args, **kwargs)
584
585   ``LinearRing`` objects are constructed in the exact same way as
586   :class:`LineString` objects, however the coordinates must be
587   *closed*, in other words, the first coordinates must be the
588   same as the last coordinates.  For example::
589
590       >>> ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))
591
592   Notice that ``(0, 0)`` is the first and last coordinate -- if
593   they were not equal, an error would be raised.
594
595``Polygon``
596-----------
597
598.. class:: Polygon(*args, **kwargs)
599
600   ``Polygon`` objects may be instantiated by passing in one or
601   more parameters that represent the rings of the polygon.  The
602   parameters must either be :class:`LinearRing` instances, or
603   a sequence that may be used to construct a :class:`LinearRing`::
604
605       >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
606       >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))
607       >>> poly = Polygon(ext_coords, int_coords)
608       >>> poly = Polygon(LinearRing(ext_coords), LinearRing(int_coords))
609
610   .. classmethod:: from_bbox(bbox)
611
612   Returns a polygon object from the given bounding-box, a 4-tuple
613   comprising (xmin, ymin, xmax, ymax).
614
615   .. attribute:: num_interior_rings
616
617   Returns the number of interior rings in this geometry.
618
619Geometry Collections
620====================
621
622``MultiPoint``
623--------------
624
625.. class:: MultiPoint(*args, **kwargs)
626
627   ``MultiPoint`` objects may be instantiated by passing in one
628   or more :class:`Point` objects as arguments, or a single
629   sequence of :class:`Point` objects::
630
631       >>> mp = MultiPoint(Point(0, 0), Point(1, 1))
632       >>> mp = MultiPoint( (Point(0, 0), Point(1, 1)) )
633
634``MultiLineString``
635-------------------
636
637.. class:: MultiLineString(*args, **kwargs)
638
639   ``MultiLineString`` objects may be instantiated by passing in one
640   or more :class:`LineString` objects as arguments, or a single
641   sequence of :class:`LineString` objects::
642
643       >>> ls1 = LineString((0, 0), (1, 1))
644       >>> ls2 = LineString((2, 2), (3, 3))
645       >>> mls = MultiLineString(ls1, ls2)
646       >>> mls = MultiLineString([ls1, ls2])
647
648   .. attribute:: merged
649
650   Returns a :class:`LineString` representing the line merge of
651   all the components in this ``MultiLineString``.
652
653
654``MultiPolygon``
655----------------
656
657.. class:: MultiPolygon(*args, **kwargs)
658
659   ``MultiPolygon`` objects may be instantiated by passing one or
660   more :class:`Polygon` objects as arguments, or a single sequence
661   of :class:`Polygon` objects::
662
663       >>> p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
664       >>> p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) )
665       >>> mp = MultiPolygon(p1, p2)
666       >>> mp = MultiPolygon([p1, p2])
667
668   .. attribute:: cascaded_union
669
670   Returns a :class:`Polygon` that is the union of all of the component
671   polygons in this collection.  The algorithm employed is significantly
672   more efficient (faster) than trying to union the geometries together
673   individually. [#fncascadedunion]_
674
675   .. note::
676
677       GEOS 3.1 is *required* to peform cascaded unions.
678
679``GeometryCollection``
680----------------------
681
682.. class:: GeometryCollection(*args, **kwargs)
683
684   ``GeometryCollection`` objects may be instantiated by passing in
685   one or more other :class:`GEOSGeometry` as arguments, or a single
686   sequence of :class:`GEOSGeometry` objects::
687
688       >>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
689       >>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
690       >>> gc = GeometryCollection((Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly))
691
692.. _prepared-geometries:
693
694Prepared Geometries
695===================
696
697In order to obtain a prepared geometry, just access the
698:attr:`GEOSGeometry.prepared` property.  Once you have a
699``PreparedGeometry`` instance its spatial predicate methods, listed below,
700may be used with other ``GEOSGeometry`` objects.  An operation with a prepared
701geometry can be orders of magnitude faster -- the more complex the geometry
702that is prepared, the larger the speedup in the operation.  For more information,
703please consult the `GEOS wiki page on prepared geometries <http://trac.osgeo.org/geos/wiki/PreparedGeometry>`_.
704
705.. note::
706
707   GEOS 3.1 is *required* in order to use prepared geometries.
708
709For example::
710
711    >>> from django.contrib.gis.geos import Point, Polygon
712    >>> poly = Polygon.from_bbox((0, 0, 5, 5))
713    >>> prep_poly = poly.prepared
714    >>> prep_poly.contains(Point(2.5, 2.5))
715    True
716
717``PreparedGeometry``
718--------------------
719
720.. class:: PreparedGeometry
721
722  All methods on ``PreparedGeometry`` take an ``other`` argument, which
723  must be a :class:`GEOSGeometry` instance.
724
725  .. method:: contains(other)
726
727  .. method:: contains_properly(other)
728
729  .. method:: covers(other)
730
731  .. method:: intersects(other)
732
733Geometry Factories
734==================
735
736.. function:: fromfile(file_h)
737
738   :param file_h: input file that contains spatial data
739   :type file_h: a Python ``file`` object or a string path to the file
740   :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file
741
742Example::
743
744    >>> from django.contrib.gis.geos import fromfile
745    >>> g = fromfile('/home/bob/geom.wkt')
746
747.. function:: fromstr(string, [,srid=None])
748
749   :param string: string that contains spatial data
750   :type string: string
751   :param srid: spatial reference identifier
752   :type srid: integer
753   :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string
754
755Example::
756
757    >>> from django.contrib.gis.geos import fromstr
758    >>> pnt = fromstr('POINT(-90.5 29.5)', srid=4326)
759
760I/O Objects
761===========
762
763Reader Objects
764--------------
765
766The reader I/O classes simply return a :class:`GEOSGeometry` instance from the
767WKB and/or WKT input given to their ``read(geom)`` method.
768
769.. class:: WKBReader
770
771Example::
772
773    >>> from django.contrib.gis.geos import WKBReader
774    >>> wkb_r = WKBReader()
775    >>> wkb_r.read('0101000000000000000000F03F000000000000F03F')
776    <Point object at 0x103a88910>
777
778.. class:: WKTReader
779
780Example::
781
782    >>> from django.contrib.gis.geos import WKTReader
783    >>> wkt_r = WKTReader()
784    >>> wkt_r.read('POINT(1 1)')
785    <Point object at 0x103a88b50>
786
787Writer Objects
788--------------
789
790All writer objects have a ``write(geom)`` method that returns either the
791WKB or WKT of the given geometry.  In addition, :class:`WKBWriter` objects
792also have properties that may be used to change the byte order, and or
793include the SRID and 3D values (in other words, EWKB).
794
795.. class:: WKBWriter
796
797``WKBWriter`` provides the most control over its output.  By default it
798returns OGC-compliant WKB when it's ``write`` method is called.  However,
799it has properties that allow for the creation of EWKB, a superset of the
800WKB standard that includes additional information.
801
802.. method:: WKBWriter.write(geom)
803
804Returns the WKB of the given geometry as a Python ``buffer`` object.
805Example::
806
807    >>> from django.contrib.gis.geos import Point, WKBWriter
808    >>> pnt = Point(1, 1)
809    >>> wkb_w = WKBWriter()
810    >>> wkb_w.write(pnt)
811    <read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930>
812
813.. method:: WKBWriter.write_hex(geom)
814
815Returns WKB of the geometry in hexadecimal.  Example::
816
817    >>> from django.contrib.gis.geos import Point, WKBWriter
818    >>> pnt = Point(1, 1)
819    >>> wkb_w = WKBWriter()
820    >>> wkb_w.write_hex(pnt)
821    '0101000000000000000000F03F000000000000F03F'
822
823.. attribute:: WKBWriter.byteorder
824
825This property may be be set to change the byte-order of the geometry
826representation.
827
828=============== =================================================
829Byteorder Value Description
830=============== =================================================
8310               Big Endian (e.g., compatible with RISC systems)
8321               Little Endian (e.g., compatible with x86 systems)
833=============== =================================================
834
835Example::
836
837    >>> from django.contrib.gis.geos import Point, WKBWriter
838    >>> wkb_w = WKBWriter()
839    >>> pnt = Point(1, 1)
840    >>> wkb_w.write_hex(pnt)
841    '0101000000000000000000F03F000000000000F03F'
842    >>> wkb_w.byteorder = 0
843    '00000000013FF00000000000003FF0000000000000'
844
845.. attribute:: WKBWriter.outdim
846
847This property may be set to change the output dimension of the geometry
848representation.  In other words, if you have a 3D geometry then set to 3
849so that the Z value is included in the WKB.
850
851============ ===========================
852Outdim Value Description
853============ ===========================
8542            The default, output 2D WKB.
8553            Output 3D EWKB.
856============ ===========================
857
858Example::
859
860    >>> from django.contrib.gis.geos import Point, WKBWriter
861    >>> wkb_w = WKBWriter()
862    >>> wkb_w.outdim
863    2
864    >>> pnt = Point(1, 1, 1)
865    >>> wkb_w.write_hex(pnt) # By default, no Z value included:
866    '0101000000000000000000F03F000000000000F03F'
867    >>> wkb_w.outdim = 3 # Tell writer to include Z values
868    >>> wkb_w.write_hex(pnt)
869    '0101000080000000000000F03F000000000000F03F000000000000F03F'
870
871.. attribute:: WKBWriter.srid
872
873Set this property with a boolean to indicate whether the SRID of the
874geometry should be included with the WKB representation.  Example::
875
876    >>> from django.contrib.gis.geos import Point, WKBWriter
877    >>> wkb_w = WKBWriter()
878    >>> pnt = Point(1, 1, srid=4326)
879    >>> wkb_w.write_hex(pnt) # By default, no SRID included:
880    '0101000000000000000000F03F000000000000F03F'
881    >>> wkb_w.srid = True # Tell writer to include SRID
882    >>> wkb_w.write_hex(pnt)
883    '0101000020E6100000000000000000F03F000000000000F03F'
884
885.. class:: WKTWriter
886
887.. method:: WKTWriter.write(geom)
888
889Returns the WKT of the given geometry. Example::
890
891    >>> from django.contrib.gis.geos import Point, WKTWriter
892    >>> pnt = Point(1, 1)
893    >>> wkt_w = WKTWriter()
894    >>> wkt_w.write(pnt)
895    'POINT (1.0000000000000000 1.0000000000000000)'
896
897
898.. rubric:: Footnotes
899.. [#fnogc] *See* `PostGIS EWKB, EWKT and Canonical Forms <http://postgis.refractions.net/docs/ch04.html#id2591381>`_, PostGIS documentation at Ch. 4.1.2.
900.. [#fncascadedunion] For more information, read Paul Ramsey's blog post about `(Much) Faster Unions in PostGIS 1.4 <http://blog.cleverelephant.ca/2009/01/must-faster-unions-in-postgis-14.html>`_ and Martin Davis' blog post on `Fast polygon merging in JTS using Cascaded Union <http://lin-ear-th-inking.blogspot.com/2007/11/fast-polygon-merging-in-jts-using.html>`_.
901
902Settings
903========
904
905.. setting:: GEOS_LIBRARY_PATH
906
907GEOS_LIBRARY_PATH
908-----------------
909
910A string specifying the location of the GEOS C library.  Typically,
911this setting is only used if the GEOS C library is in a non-standard
912location (e.g., ``/home/bob/lib/libgeos_c.so``).
913
914.. note::
915
916    The setting must be the *full* path to the **C** shared library; in
917    other words you want to use ``libgeos_c.so``, not ``libgeos.so``.