GEOS stands for Geometry Engine  Open Source, and is a C++ library, ported from the Java Topology Suite. GEOS implements the OpenGIS Simple Features for SQL spatial predicate functions and spatial operators. GEOS, now an OSGeo project, was initially developed and maintained by Refractions Research of Victoria, Canada.
GeoDjango implements a highlevel Python wrapper for the GEOS library, its features include:
ctypes
.GEOSGeometry
objects
may be used outside of a django project/application. In other words,
no need to have DJANGO_SETTINGS_MODULE
set or use a database, etc.GEOSGeometry
objects may be modified.This section contains a brief introduction and tutorial to using
GEOSGeometry
objects.
GEOSGeometry
objects may be created in a few ways. The first is
to simply instantiate the object on some spatial input – the following
are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON:
>>> from django.contrib.gis.geos import GEOSGeometry
>>> pnt = GEOSGeometry('POINT(5 23)') # WKT
>>> pnt = GEOSGeometry('010100000000000000000014400000000000003740') # HEX
>>> pnt = GEOSGeometry(buffer('\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14@\x00\x00\x00\x00\x00\x007@'))
>>> pnt = GEOSGeometry('{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }') # GeoJSON
Another option is to use the constructor for the specific geometry type
that you wish to create. For example, a Point
object may be
created by passing in the X and Y coordinates into its constructor:
>>> from django.contrib.gis.geos import Point
>>> pnt = Point(5, 23)
Finally, there are fromstr()
and fromfile()
factory methods, which
return a GEOSGeometry
object from an input string or a file:
>>> from django.contrib.gis.geos import fromstr, fromfile
>>> pnt = fromstr('POINT(5 23)')
>>> pnt = fromfile('/path/to/pnt.wkt')
>>> pnt = fromfile(open('/path/to/pnt.wkt'))
GEOSGeometry
objects are ‘Pythonic’, in other words components may
be accessed, modified, and iterated over using standard Python conventions.
For example, you can iterate over the coordinates in a Point
:
>>> pnt = Point(5, 23)
>>> [coord for coord in pnt]
[5.0, 23.0]
With any geometry object, the GEOSGeometry.coords
property
may be used to get the geometry coordinates as a Python tuple:
>>> pnt.coords
(5.0, 23.0)
You can get/set geometry components using standard Python indexing
techniques. However, what is returned depends on the geometry type
of the object. For example, indexing on a LineString
returns a coordinate tuple:
>>> from django.contrib.gis.geos import LineString
>>> line = LineString((0, 0), (0, 50), (50, 50), (50, 0), (0, 0))
>>> line[0]
(0.0, 0.0)
>>> line[2]
(50.0, 0.0)
Whereas indexing on a Polygon
will return the ring
(a LinearRing
object) corresponding to the index:
>>> from django.contrib.gis.geos import Polygon
>>> poly = Polygon( ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)) )
>>> poly[0]
<LinearRing object at 0x1044395b0>
>>> poly[0][2] # secondtolast coordinate of external ring
(50.0, 0.0)
In addition, coordinates/components of the geometry may added or modified, just like a Python list:
>>> line[0] = (1.0, 1.0)
>>> line.pop()
(0.0, 0.0)
>>> line.append((1.0, 1.0))
>>> line.coords
((1.0, 1.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (1.0, 1.0))
GEOSGeometry
¶GEOSGeometry
(geo_input[, srid=None])¶Parameters: 


This is the base class for all GEOS geometry objects. It initializes on the
given geo_input
argument, and then assumes the proper geometry subclass
(e.g., GEOSGeometry('POINT(1 1)')
will create a Point
object).
The following input formats, along with their corresponding Python types, are accepted:
Format  Input Type 

WKT / EWKT  str or unicode 
HEX / HEXEWKB  str or unicode 
WKB / EWKB  buffer 
GeoJSON  str or unicode 
GEOSGeometry.
coords
¶Returns the coordinates of the geometry as a tuple.
GEOSGeometry.
empty
¶Returns whether or not the set of points in the geometry is empty.
GEOSGeometry.
geom_type
¶Returns a string corresponding to the type of geometry. For example:
>>> pnt = GEOSGeometry('POINT(5 23)')
>>> pnt.geom_type
'Point'
GEOSGeometry.
geom_typeid
¶Returns the GEOS geometry type identification number. The following table shows the value for each geometry type:
Geometry  ID 

Point 
0 
LineString 
1 
LinearRing 
2 
Polygon 
3 
MultiPoint 
4 
MultiLineString 
5 
MultiPolygon 
6 
GeometryCollection 
7 
GEOSGeometry.
num_coords
¶Returns the number of coordinates in the geometry.
GEOSGeometry.
num_geom
¶Returns the number of geometries in this geometry. In other words, will return 1 on anything but geometry collections.
GEOSGeometry.
hasz
¶Returns a boolean indicating whether the geometry is threedimensional.
GEOSGeometry.
ring
¶Returns a boolean indicating whether the geometry is a LinearRing
.
GEOSGeometry.
simple
¶Returns a boolean indicating whether the geometry is ‘simple’. A geometry
is simple if and only if it does not intersect itself (except at boundary
points). For example, a LineString
object is not simple if it
intersects itself. Thus, LinearRing
and :class`Polygon` objects
are always simple because they do cannot intersect themselves, by
definition.
GEOSGeometry.
valid
¶Returns a boolean indicating whether the geometry is valid.
GEOSGeometry.
valid_reason
¶Returns a string describing the reason why a geometry is invalid.
GEOSGeometry.
srid
¶Property that may be used to retrieve or set the SRID associated with the geometry. For example:
>>> pnt = Point(5, 23)
>>> print pnt.srid
None
>>> pnt.srid = 4326
>>> pnt.srid
4326
The properties in this section export the GEOSGeometry
object into
a different. This output may be in the form of a string, buffer, or even
another object.
GEOSGeometry.
ewkt
¶Returns the “extended” WellKnown Text of the geometry. This representation
is specific to PostGIS and is a super set of the OGC WKT standard. [1]
Essentially the SRID is prepended to the WKT representation, for example
SRID=4326;POINT(5 23)
.
Note
The output from this property does not include the 3dm, 3dz, and 4d information that PostGIS supports in its EWKT representations.
GEOSGeometry.
hex
¶Returns the WKB of this Geometry in hexadecimal form. Please note
that the SRID and Z values are not included in this representation
because it is not a part of the OGC specification (use the
GEOSGeometry.hexewkb
property instead).
GEOSGeometry.
hexewkb
¶Returns the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes SRID and Z values that are a part of this geometry.
Note
GEOS 3.1 is required if you want valid 3D HEXEWKB.
GEOSGeometry.
json
¶Returns the GeoJSON representation of the geometry.
Note
Requires GDAL.
GEOSGeometry.
geojson
¶Alias for GEOSGeometry.json
.
GEOSGeometry.
kml
¶Returns a KML (Keyhole Markup Language) representation of the geometry. This should only be used for geometries with an SRID of 4326 (WGS84), but this restriction is not enforced.
GEOSGeometry.
ogr
¶Returns an OGRGeometry
object
correspondg to the GEOS geometry.
Note
Requires GDAL.
GEOSGeometry.
wkb
¶Returns the WKB (WellKnown Binary) representation of this Geometry
as a Python buffer. SRID and Z values are not included, use the
GEOSGeometry.ewkb
property instead.
GEOSGeometry.
ewkb
¶Return the EWKB representation of this Geometry as a Python buffer. This is an extension of the WKB specification that includes any SRID and Z values that are a part of this geometry.
Note
GEOS 3.1 is required if you want valid 3D EWKB.
GEOSGeometry.
wkt
¶Returns the WellKnown Text of the geometry (an OGC standard).
All of the following spatial predicate methods take another
GEOSGeometry
instance (other
) as a parameter, and
return a boolean.
GEOSGeometry.
contains
(other)¶Returns True
if GEOSGeometry.within()
is False
.
GEOSGeometry.
crosses
(other)¶Returns True
if the DE9IM intersection matrix for the two Geometries
is T*T******
(for a point and a curve,a point and an area or a line
and an area) 0********
(for two curves).
GEOSGeometry.
disjoint
(other)¶Returns True
if the DE9IM intersection matrix for the two geometries
is FF*FF****
.
GEOSGeometry.
equals
(other)¶Returns True
if the DE9IM intersection matrix for the two geometries
is T*F**FFF*
.
GEOSGeometry.
equals_exact
(other, tolerance=0)¶Returns true if the two geometries are exactly equal, up to a
specified tolerance. The tolerance
value should be a floating
point number representing the error tolerance in the comparison, e.g.,
poly1.equals_exact(poly2, 0.001)
will compare equality to within
one thousandth of a unit.
GEOSGeometry.
intersects
(other)¶Returns True
if GEOSGeometry.disjoint()
is False
.
GEOSGeometry.
overlaps
(other)¶Returns true if the DE9IM intersection matrix for the two geometries
is T*T***T**
(for two points or two surfaces) 1*T***T**
(for two curves).
GEOSGeometry.
relate_pattern
(other, pattern)¶Returns True
if the elements in the DE9IM intersection matrix
for this geometry and the other matches the given pattern
–
a string of nine characters from the alphabet: {T
, F
, *
, 0
}.
GEOSGeometry.
touches
(other)¶Returns True
if the DE9IM intersection matrix for the two geometries
is FT*******
, F**T*****
or F***T****
.
GEOSGeometry.
within
(other)¶Returns True
if the DE9IM intersection matrix for the two geometries
is T*F**F***
.
GEOSGeometry.
buffer
(width, quadsegs=8)¶Returns a GEOSGeometry
that represents all points whose distance
from this geometry is less than or equal to the given width
. The optional
quadsegs
keyword sets the number of segments used to approximate a
quarter circle (defaults is 8).
GEOSGeometry.
difference
(other)¶Returns a GEOSGeometry
representing the points making up this
geometry that do not make up other.
GEOSGeometry:intersection(other)
Returns a GEOSGeometry
representing the points shared by this
geometry and other.
GEOSGeometry.
relate
(other)¶Returns the DE9IM intersection matrix (a string) representing the topological relationship between this geometry and the other.
GEOSGeometry.
simplify
(tolerance=0.0, preserve_topology=False)¶Returns a new GEOSGeometry
, simplified using the DouglasPeucker
algorithm to the specified tolerance. A higher tolerance value implies
less points in the output. If no tolerance is tolerance provided,
it defaults to 0.
By default, this function does not preserve topology  e.g.,
Polygon
objects can be split, collapsed into lines or disappear.
Polygon
holes can be created or disappear, and lines can cross.
By specifying preserve_topology=True
, the result will have the same
dimension and number of components as the input, however, this is
significantly slower.
GEOSGeometry.
sym_difference
(other)¶Returns a GEOSGeometry
combining the points in this geometry
not in other, and the points in other not in this geometry.
GEOSGeometry.
union
(other)¶Returns a GEOSGeometry
representing all the points in this
geometry and the other.
GEOSGeometry.
boundary
¶Returns the boundary as a newly allocated Geometry object.
GEOSGeometry.
centroid
¶Returns a Point
object representing the geometric center of
the geometry. The point is not guaranteed to be on the interior
of the geometry.
GEOSGeometry.
convex_hull
¶Returns the smallest Polygon
that contains all the points in
the geometry.
GEOSGeometry.
envelope
¶Returns a Polygon
that represents the bounding envelope of
this geometry.
GEOSGeometry.
point_on_surface
¶Computes and returns a Point
guaranteed to be on the interior
of this geometry.
GEOSGeometry.
area
¶This property returns the area of the Geometry.
GEOSGeometry.
extent
¶This property returns the extent of this geometry as a 4tuple, consisting of (xmin, ymin, xmax, ymax).
GEOSGeometry.
clone
()¶This method returns a GEOSGeometry
that is a clone of the original.
GEOSGeometry.
distance
(geom)¶Returns the distance between the closest points on this geometry and the given
geom
(another GEOSGeometry
object).
Note
GEOS distance calculations are linear – in other words, GEOS does not perform a spherical calculation even if the SRID specifies a geographic coordinate system.
GEOSGeometry.
length
¶Returns the length of this geometry (e.g., 0 for a Point
,
the length of a LineString
, or the circumference of
a Polygon
).
GEOSGeometry.
prepared
¶Note
Support for prepared geometries requires GEOS 3.1.
Returns a GEOS PreparedGeometry
for the contents of this geometry.
PreparedGeometry
objects are optimized for the contains, intersects,
and covers operations. Refer to the Prepared Geometries documentation
for more information.
GEOSGeometry.
srs
¶Returns a SpatialReference
object
corresponding to the SRID of the geometry or None
.
Note
Requires GDAL.
GEOSGeometry.
transform
(ct, clone=False)¶Transforms the geometry according to the given coordinate transformation paramter
(ct
), which may be an integer SRID, spatial reference WKT string,
a PROJ.4 string, a SpatialReference
object, or a
CoordTransform
object. By default, the geometry
is transformed inplace and nothing is returned. However if the clone
keyword
is set, then the geometry is not modified and a transformed clone of the geometry
is returned instead.
Note
Requires GDAL.
Note
Prior to 1.3, this method would silently noop if GDAL was not available.
Now, a GEOSException
is raised as
application code relying on this behavior is in error. In addition,
use of this method when the SRID is None
or less than 0 now generates
a warning because a GEOSException
will
be raised instead in version 1.5.
Point
¶Point
(x, y, z=None, srid=None)¶Point
objects are instantiated using arguments that represent
the component coordinates of the point or with a single sequence
coordinates. For example, the following are equivalent:
>>> pnt = Point(5, 23)
>>> pnt = Point([5, 23])
LineString
¶LineString
(*args, **kwargs)¶LineString
objects are instantiated using arguments that are
either a sequence of coordinates or Point
objects.
For example, the following are equivalent:
>>> ls = LineString((0, 0), (1, 1))
>>> ls = LineString(Point(0, 0), Point(1, 1))
In addition, LineString
objects may also be created by passing
in a single sequence of coordinate or Point
objects:
>>> ls = LineString( ((0, 0), (1, 1)) )
>>> ls = LineString( [Point(0, 0), Point(1, 1)] )
LinearRing
¶LinearRing
(*args, **kwargs)¶LinearRing
objects are constructed in the exact same way as
LineString
objects, however the coordinates must be
closed, in other words, the first coordinates must be the
same as the last coordinates. For example:
>>> ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))
Notice that (0, 0)
is the first and last coordinate – if
they were not equal, an error would be raised.
Polygon
¶Polygon
(*args, **kwargs)¶Polygon
objects may be instantiated by passing in one or
more parameters that represent the rings of the polygon. The
parameters must either be LinearRing
instances, or
a sequence that may be used to construct a LinearRing
:
>>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))
>>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))
>>> poly = Polygon(ext_coords, int_coords)
>>> poly = Polygon(LinearRing(ext_coords), LinearRing(int_coords))
from_bbox
(bbox)¶Returns a polygon object from the given boundingbox, a 4tuple comprising (xmin, ymin, xmax, ymax).
num_interior_rings
¶Returns the number of interior rings in this geometry.
MultiPoint
¶MultiLineString
¶MultiLineString
(*args, **kwargs)¶MultiLineString
objects may be instantiated by passing in one
or more LineString
objects as arguments, or a single
sequence of LineString
objects:
>>> ls1 = LineString((0, 0), (1, 1))
>>> ls2 = LineString((2, 2), (3, 3))
>>> mls = MultiLineString(ls1, ls2)
>>> mls = MultiLineString([ls1, ls2])
merged
¶Returns a LineString
representing the line merge of
all the components in this MultiLineString
.
MultiPolygon
¶MultiPolygon
(*args, **kwargs)¶MultiPolygon
objects may be instantiated by passing one or
more Polygon
objects as arguments, or a single sequence
of Polygon
objects:
>>> p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
>>> p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) )
>>> mp = MultiPolygon(p1, p2)
>>> mp = MultiPolygon([p1, p2])
cascaded_union
¶Returns a Polygon
that is the union of all of the component
polygons in this collection. The algorithm employed is significantly
more efficient (faster) than trying to union the geometries together
individually. [2]
Note
GEOS 3.1 is required to peform cascaded unions.
GeometryCollection
¶GeometryCollection
(*args, **kwargs)¶GeometryCollection
objects may be instantiated by passing in
one or more other GEOSGeometry
as arguments, or a single
sequence of GEOSGeometry
objects:
>>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
>>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)
>>> gc = GeometryCollection((Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly))
In order to obtain a prepared geometry, just access the
GEOSGeometry.prepared
property. Once you have a
PreparedGeometry
instance its spatial predicate methods, listed below,
may be used with other GEOSGeometry
objects. An operation with a prepared
geometry can be orders of magnitude faster – the more complex the geometry
that is prepared, the larger the speedup in the operation. For more information,
please consult the GEOS wiki page on prepared geometries.
Note
GEOS 3.1 is required in order to use prepared geometries.
For example:
>>> from django.contrib.gis.geos import Point, Polygon
>>> poly = Polygon.from_bbox((0, 0, 5, 5))
>>> prep_poly = poly.prepared
>>> prep_poly.contains(Point(2.5, 2.5))
True
fromfile
(file_h)¶Parameters:  file_h (a Python file object or a string path to the file) – input file that contains spatial data 

Return type:  a GEOSGeometry corresponding to the spatial data in the file 
Example:
>>> from django.contrib.gis.geos import fromfile
>>> g = fromfile('/home/bob/geom.wkt')
fromstr
(string[, srid=None])¶Parameters: 


Return type:  a 
Example:
>>> from django.contrib.gis.geos import fromstr
>>> pnt = fromstr('POINT(90.5 29.5)', srid=4326)
The reader I/O classes simply return a GEOSGeometry
instance from the
WKB and/or WKT input given to their read(geom)
method.
WKBReader
¶Example:
>>> from django.contrib.gis.geos import WKBReader
>>> wkb_r = WKBReader()
>>> wkb_r.read('0101000000000000000000F03F000000000000F03F')
<Point object at 0x103a88910>
WKTReader
¶Example:
>>> from django.contrib.gis.geos import WKTReader
>>> wkt_r = WKTReader()
>>> wkt_r.read('POINT(1 1)')
<Point object at 0x103a88b50>
All writer objects have a write(geom)
method that returns either the
WKB or WKT of the given geometry. In addition, WKBWriter
objects
also have properties that may be used to change the byte order, and or
include the SRID and 3D values (in other words, EWKB).
WKBWriter
¶WKBWriter
provides the most control over its output. By default it
returns OGCcompliant WKB when it’s write
method is called. However,
it has properties that allow for the creation of EWKB, a superset of the
WKB standard that includes additional information.
WKBWriter.
write
(geom)¶Returns the WKB of the given geometry as a Python buffer
object.
Example:
>>> from django.contrib.gis.geos import Point, WKBWriter
>>> pnt = Point(1, 1)
>>> wkb_w = WKBWriter()
>>> wkb_w.write(pnt)
<readonly buffer for 0x103a898f0, size 1, offset 0 at 0x103a89930>
WKBWriter.
write_hex
(geom)¶Returns WKB of the geometry in hexadecimal. Example:
>>> from django.contrib.gis.geos import Point, WKBWriter
>>> pnt = Point(1, 1)
>>> wkb_w = WKBWriter()
>>> wkb_w.write_hex(pnt)
'0101000000000000000000F03F000000000000F03F'
WKBWriter.
byteorder
¶This property may be be set to change the byteorder of the geometry representation.
Byteorder Value  Description 

0  Big Endian (e.g., compatible with RISC systems) 
1  Little Endian (e.g., compatible with x86 systems) 
Example:
>>> from django.contrib.gis.geos import Point, WKBWriter
>>> wkb_w = WKBWriter()
>>> pnt = Point(1, 1)
>>> wkb_w.write_hex(pnt)
'0101000000000000000000F03F000000000000F03F'
>>> wkb_w.byteorder = 0
'00000000013FF00000000000003FF0000000000000'
WKBWriter.
outdim
¶This property may be set to change the output dimension of the geometry representation. In other words, if you have a 3D geometry then set to 3 so that the Z value is included in the WKB.
Outdim Value  Description 

2  The default, output 2D WKB. 
3  Output 3D EWKB. 
Example:
>>> from django.contrib.gis.geos import Point, WKBWriter
>>> wkb_w = WKBWriter()
>>> wkb_w.outdim
2
>>> pnt = Point(1, 1, 1)
>>> wkb_w.write_hex(pnt) # By default, no Z value included:
'0101000000000000000000F03F000000000000F03F'
>>> wkb_w.outdim = 3 # Tell writer to include Z values
>>> wkb_w.write_hex(pnt)
'0101000080000000000000F03F000000000000F03F000000000000F03F'
WKBWriter.
srid
¶Set this property with a boolean to indicate whether the SRID of the geometry should be included with the WKB representation. Example:
>>> from django.contrib.gis.geos import Point, WKBWriter
>>> wkb_w = WKBWriter()
>>> pnt = Point(1, 1, srid=4326)
>>> wkb_w.write_hex(pnt) # By default, no SRID included:
'0101000000000000000000F03F000000000000F03F'
>>> wkb_w.srid = True # Tell writer to include SRID
>>> wkb_w.write_hex(pnt)
'0101000020E6100000000000000000F03F000000000000F03F'
WKTWriter
¶WKTWriter.
write
(geom)¶Returns the WKT of the given geometry. Example:
>>> from django.contrib.gis.geos import Point, WKTWriter
>>> pnt = Point(1, 1)
>>> wkt_w = WKTWriter()
>>> wkt_w.write(pnt)
'POINT (1.0000000000000000 1.0000000000000000)'
Footnotes
[1]  See PostGIS EWKB, EWKT and Canonical Forms, PostGIS documentation at Ch. 4.1.2. 
[2]  For more information, read Paul Ramsey’s blog post about (Much) Faster Unions in PostGIS 1.4 and Martin Davis’ blog post on Fast polygon merging in JTS using Cascaded Union. 
A string specifying the location of the GEOS C library. Typically,
this setting is only used if the GEOS C library is in a nonstandard
location (e.g., /home/bob/lib/libgeos_c.so
).
Note
The setting must be the full path to the C shared library; in
other words you want to use libgeos_c.so
, not libgeos.so
.
Nov 29, 2016