GDAL stands for Geospatial Data Abstraction Library, and is a veritable “swiss army knife” of GIS data functionality. It also includes the OGR Simple Features Library, which specializes in reading and writing geographic data in a variety of standard formats.
The GDAL/OGR tools described here are designed to help you read in your geospatial data, in order for most of them to be useful you have to have some data to work with. If you’re starting out and don’t yet have any data of your own to use, GeoDjango comes with a number of simple data sets that you can use for testing. This snippet will determine where these sample files are installed on your computer.
>>> import os
>>> import django.contrib.gis
>>> GIS_PATH = os.path.dirname(django.contrib.gis.__file__)
>>> CITIES_PATH = os.path.join(GIS_PATH, 'tests/layermap/cities/cities.shp')
DataSource is a wrapper for the OGR data source object that supports reading data from a variety of OGR-supported geospatial file formats and data sources using a simple, consistent interface. Each data source is represented by a DataSource object which contains one or more layers of data. Each layer, represented by a Layer object, contains some number of geographic features, as well as information about the type of features contained in that layer (e.g. points, polygons, etc.), as well as the names and types of any additional fields of data that may be associated with each feature in that layer.
The constructor for the DataSource object normally takes just a single parameter, the path of the file you want to read. However, OGR also supports a variety of more complex data sources, including databases, that you access by passing it a special name string instead of a path. For more information, see the OGR Vector Formats documentation. The name property of a DataSource will tell you the OGR name of the underlying data source that it is using.
Once you’ve created your DataSource, you can find out how many layers of data it contains by accessing the layer_count property, or (equivalently) by using the len() function. For information on accessing the layers of data themselves, see the next section.
>>> from django.contrib.gis.gdal import DataSource
>>> ds = DataSource(CITIES_PATH)
>>> ds.name # The exact filename may be different on your computer
'/usr/local/lib/python2.6/site-packages/django/contrib/gis/tests/layermap/cities/cities.shp'
>>> ds.layer_count # This file only contains one layer
1
Layer is a wrapper for a layer of data in a DataSource object. You never create a Layer object directly. Instead, you retreive them from a DataSource object, which is essentially a standard Python container of Layer objects. For example, you can access a specific layer by its index (e.g. ds[0] to access the first layer), or you can iterate over all the layers in the container in a for loop. The Layer itself acts as a container for geometric features.
All the features in a given layer have the same geometry type. The geom_type property of a layer is an OGRGeomType object, discussed below, that identifies the feature type. We can use it to print out some basic information about each layer in a datasource:
>>> for layer in ds:
... print 'Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name)
...
Layer "cities": 3 Points
The example output is from the cities data source, loaded above, which evidently contains one layer, called "cities", which contains three point features. For simplicity, the examples below assume that you’ve stored that layer in the variable layer:
>>> layer = ds[0]
Returns the geometry type of the layer, as an OGRGeomType object (see below).
>>> layer.geom_type.name
'Point'
A method that returns a list containing the geometry of each feature in the layer. If the optional argument geos is set to True then the geometries are converted to GEOS gemometry objects. Otherwise, they are returned as OGRGeometry objects (see below).
>>> [pt.tuple for pt in layer.get_geoms()]
[(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)]
Returns the number of fields in the layer, i.e the number of fields of data associated with each feature in the layer.
>>> layer.num_fields
4
Returns a list of the names of each of the fields in this layer.
>>> layer.fields
['Name', 'Population', 'Density', 'Created']
Returns a list of the data types of each of the fields in this layer. These are subclasses of Field, discussed below.
>>> [ft.__name__ for ft in layer.field_types]
['OFTString', 'OFTReal', 'OFTReal', 'OFTDate']
A method that returns a list of the values of a given field for each feature in the layer.
>>> layer.get_fields('Name')
['Pueblo', 'Lawrence', 'Houston']
Returns a list of the maximum field widths for each of the fields in this layer.
>>> layer.field_widths
[80, 11, 24, 10]
Returns a list of the numeric precisions for each of the fields in this layer. This is meaningless (and set to zero) for non-numeric fields.
>>> layer.field_precisions
[0, 0, 15, 0]
Returns the spatial extent of this layer, as an Envelope object (see below).
>>> layer.extent.tuple
(-104.609252, 29.763374, -95.23506, 38.971823)
Returns the spatial reference system used in this layer, as a SpatialReference object (see below).
>>> layer.srs.name
'GCS_WGS_1984'
Feature wraps an OGR feature. You never create a Feature object directly. Instead, you retreive them from a Layer object. Each feature consists of a geometry and a set of fields containing additional properties. The geometry of a field is accessible via its geom property, which returns an OGRGeometry object (discussed below). A Feature behaves like a standard Python container for its fields, which it returns as Field objects: you can access a field directly by its index or name, or you can iterate over a feature’s fields, e.g. in a for loop.
Returns the geometry for this feature, as an OGRGeometry object.
>>> city.geom.tuple
(-104.609252, 38.255001)
A method that returns the value of the given field (specified by name) for this feature, not a Field wrapper object.
>>> city.get('Population')
102121
Returns the type of geometry for this feature, as an OGRGeomType object. This will be the same for all features in a given layer, and is equivalent to the geom_type property of the Layer object itself.
Returns the number of fields of data associated with the feature. This will be the same for all features in a given layer, and is equivalent to the num_fields property of the Layer object itself.
Returns a list of the names of the fields of data associated with the feature. This will be the same for all features in a given layer, and is equivalent to the fields property of the Layer object itself.
Returns the name of the layer that the feature came from. This will be the same for all features in a given layer.
>>> city.layer_name
'cities'
A method that returns the index of the given field name. This will be the same for all features in a given layer.
>>> city.index('Population')
1
>>> name = city['Name']
Returns the OGR type of this field, as an integer. The FIELD_CLASSES dictionary maps these values onto subclasses of Field.
>>> city['Density'].type
2
Returns a string with the name of the data type of this field.
>>> city['Name'].type_name
'String'
Returns the value of this field. The Field class itself returns the value as a string, but each subclass returns the value in the most appropriate form.
>>> city['Population'].value
102121
Returns the numeric precision of this field. This is meaningless (and set to zero) for non-numeric fields.
>>> city['Density'].precision
15
Returns the value of the field as a double (float).
>>> city['Density'].as_double()
874.7
Returns the value of the field as a tuple of date and time components.
>>> city['Created'].as_datetime()
(c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))
Driver is used internally to wrap an OGR data source driver.
OGRGeometry is a wrapper for the OGR Geometry class. OGRGeometry objects can be instantiated from a string containing a geometry object in WKT or HEX WKB format, a buffer containing WKB data, or an OGRGeomType object. They are also returned when reading geometry data from OGR data sources via a DataSource object.
OGRGeometry objects share some functionality with GEOSGeometry objects. OGRGeometry objects are thin wrappers around OGR geometry objects, and so they allow for more efficient access to data when using DataSource. Also, unlike its GEOS counterpart, OGRGeometry supports spatial reference systems and their transformation.
>>> from django.contrib.gis.gdal import OGRGeometry
>>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))')
Returns the number of coordinated dimensions of the geometry, i.e. 0 for points, 1 for lines, and so forth.
>> polygon.dimension 2
These identical properties each return the number of points used to describe this geometry.
>>> polygon.point_count
4
Returns the type of this geometry, as an OGRGeomType object.
Returns the area of this geometry, or 0 for geometries that do not contain an area.
>>> polygon.area
25.0
Returns the envelope of this geometry, as an Envelope object.
Returns the envelope of this geometry as a 4-tuple, instead of as an Envelope object.
>>> point.extent
(0.0, 0.0, 5.0, 5.0)
This property controls the spatial reference for this geometry, or None if no spatial reference system has been assigned to it. You can get or set this property as a SpatialReference object.
>>> city.geom.srs.name
'GCS_WGS_1984'
This property controls the spatial reference for this geometry, or None if no spatial reference system has been assigned to it. You can get or set this property as an integer ID.
Returns a GEOSGeometry object corresponding to this geometry.
Returns a string representation of this geometry in GML format.
>>> OGRGeometry('POINT(1 2)').gml
'<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
Returns a string representation of this geometry in HEX WKB format.
>>> OGRGeometry('POINT(1 2)').hex
'0101000000000000000000F03F0000000000000040'
Returns a string representation of this geometry in JSON format.
>>> OGRGeometry('POINT(1 2)').hex
'{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
Returns the size of the WKB buffer needed to hold a WKB representation of this geometry.
>>> OGRGeometry('POINT(1 2)').wkb_size
21
Returns a buffer containing a WKB representation of this geometry.
Returns a string representation of this geometry in WKT format.
Clones this geometry obect.
If there are any rings within this geometry that have not been closed, this routine will do so by adding the starting point to the end.
>>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')
>>> triangle.close_rings()
>>> triangle.wkt
'LINEARRING (0 0,0 1,1 0,0 0)'
Transforms this geometry to a different spatial reference system. May take a CoordTransform object, a SpatialReference object, a WKT or PROJ.4 string, or an integer SRID. By default nothing is returned and the geometry is transformed in-place. However, if the clone argument is set to True then a transformed clone of this geometry will be returned instead.
Returns True if this geometry intersects the other, otherwise returns False.
Returns True if this geometry is equivalent to the other, otherwise returns False.
Returns True if this geometry is spatially disjoint to (i.e. does not intersect) the other, otherwise returns False.
Returns True if this geometry touches the other, otherwise returns False.
Returns True if this geometry crosses the other, otherwise returns False.
Returns True if this geometry is contained within the other, otherwise returns False.
Returns True if this geometry contains the other, otherwise returns False.
Returns True if this geometry overlaps the other, otherwise returns False.
The boundary of this geometry, as a new OGRGeometry object.
The smallest convex polygon that contains this geometry, as a new OGRGeometry object.
Returns the region consisting of the difference of this geometry and the other, as a new OGRGeometry object.
Returns the region consisting of the intersection of this geometry and the other, as a new OGRGeometry object.
Returns the region consisting of the symmetric difference of this geometry and the other, as a new OGRGeometry object.
Returns the region consisting of the union of this geometry and the other, as a new OGRGeometry object.
Returns the X coordinate of a point geometry, or a list of X coordinates of a LineString geometry. Not applicable to other geometry types.
>>> OGRGeometry('POINT (1 2)').x
1.0
>>> OGRGeometry('LINESTRING (1 2,3 4)').x
[1.0, 3.0]
Returns the X coordinate of a point geometry, or a list of X coordinates of a LineString geometry. Not applicable to other geometry types.
>>> OGRGeometry('POINT (1 2)').y
2.0
>>> OGRGeometry('LINESTRING (1 2,3 4)').y
[2.0, 4.0]
Returns the Z coordinate of a point geometry, or a list of Z coordinates of a LineString geometry. Returns None if the geometry does not have Z coordinates. Not applicable to other geometry types.
>>> OGRGeometry('POINT (1 2 3)').z
3.0
>>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z
[3.0, 6.0]
Returns the coordinates of a point geometry as a tuple, the coordinates of a line geometry as a tuple of tuples, and so forth.
>>> OGRGeometry('POINT (1 2)').tuple
(1.0, 2.0)
>>> OGRGeometry('LINESTRING (1 2,3 4)').tuple
((1.0, 2.0), (3.0, 4.0))
Adds a geometry to this GeometryCollection. Not applicable to other geometry types.
Returns the shell or exterior ring of this polygon, as a LinearRing geometry. Not applicable to other geometry types.
Returns the number of points in a LineString, of the number of interor rings in a Polygon, or the number of geometries in a GeometryCollection. Not applicable to other geometry types.
Iterates over the points in a LineString, of the interor rings in a Polygon, or the geometries in a GeometryCollection. Not applicable to other geometry types.
Returns the point at the specified index for this LineString, or the interior ring at the specified index for this Polygon, or the geometry at the specified index for this GeometryCollection. Not applicable to other geometry types.
The OGRGeomType class is makes it easy to specify an OGR geometry type in any of several ways.
>>> from django.contrib.gis.gdal import OGRGeomType
>>> gt1 = OGRGeomType(3) # Using an integer for the type
>>> gt2 = OGRGeomType('Polygon') # Using a string
>>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
>>> print gt1 == 3, gt1 == 'Polygon' # Equivalence works w/non-OGRGeomType objects
True True
Returns the Django field type (a subclass of GeometryField) to use for storing this OGR type, or None if there is no appropriate Django type.
>>> gt1.django
'PolygonField'
CoordTransform represents a coordinate system transform. It is initalized with two SpatialReference, representing the source and target coordinate systems, respectively.
Envelope represents an OGR Evenlope structure that contains the minimum and maximum X, Y coordinates for a rectangle bounding box. The naming of the variables is compatible with the OGR Envelope structure.
The value of the minimum X coordinate.
The value of the maximum X coordinate.
The value of the minimum Y coordinate.
The value of the maximum Y coordinate.
The upper-right coordinate, as a tuple.
The lower-left coordinate, as a tuple.
A tuple representing the envelope.
A string representing this envelope as a polygon in WKT format.