GDAL stands for Geospatial Data Abstraction Library, and is a veritable “Swiss army knife” of GIS data functionality. A subset of GDAL is the OGR Simple Features Library, which specializes in reading and writing vector geographic data in a variety of standard formats.
GeoDjango provides a high-level Python interface for some of the capabilities of OGR, including the reading and coordinate transformation of vector spatial data and minimal support for GDAL’s features with respect to raster (image) data.
Note
Although the module is named gdal, GeoDjango only supports some of the capabilities of OGR and GDAL’s raster features at this time.
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 tests contain a number of data sets that you can use for testing. You can download them here:
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 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 (Feature), 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 (Field) of data that may be associated with each feature in that layer.
The constructor for DataSource only requires one parameter: the path of the file you want to read. However, OGR also supports a variety of more complex data sources, including databases, that may be accessed by passing a special name string instead of a path. For more information, see the OGR Vector Formats documentation. The name property of a DataSource instance gives the OGR name of the underlying data source that it is using.
The optional encoding parameter allows you to specify a non-standard encoding of the strings in the source. This is typically useful when you obtain DjangoUnicodeDecodeError exceptions while reading field values.
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:
Returns the number of layers in the data source.
Returns the name of the data source.
Support for pathlib.Path ds_input was added.
Layer is a wrapper for a layer of data in a DataSource object. You never create a Layer object directly. Instead, you retrieve 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.
Typically, all the features in a given layer have the same geometry type. The geom_type property of a layer is an OGRGeomType that identifies the feature type. We can use it to print out some basic information about each layer in a DataSource:
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:
Returns the name of this layer in the data source.
Returns the number of features in the layer. Same as len(layer):
Returns the geometry type of the layer, as an OGRGeomType object:
Returns the number of fields in the layer, i.e the number of fields of data associated with each feature in the layer:
Returns a list of the names of each of the fields in this layer:
Returns a list of the data types of each of the fields in this layer. These are subclasses of Field, discussed below:
Returns a list of the maximum field widths for each of the fields in this layer:
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:
Returns the spatial extent of this layer, as an Envelope object:
Property that returns the SpatialReference associated with this layer:
If the Layer has no spatial reference information associated with it, None is returned.
Property that may be used to retrieve or set a spatial filter for this layer. A spatial filter can only be set with an OGRGeometry instance, a 4-tuple extent, or None. When set with something other than None, only features that intersect the filter will be returned when iterating over the layer:
A method that returns a list of the values of a given field for each feature in the layer:
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 GEOSGeometry objects. Otherwise, they are returned as OGRGeometry objects:
Returns a boolean indicating whether this layer supports the given capability (a string). Examples of valid capability strings include: 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter', 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions', 'DeleteFeature', and 'FastSetNextByIndex'.
Feature wraps an OGR feature. You never create a Feature object directly. Instead, you retrieve 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. 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:
A method that returns the value of the given field (specified by name) for this feature, not a Field wrapper object:
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 Layer.geom_type property of the Layer object the feature came from.
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 Layer.num_fields property of the Layer object the feature came from.
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 Layer.fields property of the Layer object the feature came from.
Returns the feature identifier within the layer:
Returns the name of the Layer that the feature came from. This will be the same for all features in a given layer:
A method that returns the index of the given field name. This will be the same for all features in a given layer:
Returns the name of this field:
Returns the OGR type of this field, as an integer. The FIELD_CLASSES dictionary maps these values onto subclasses of Field:
Returns a string with the name of the data type of this field:
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:
Returns the width of this field:
Returns the numeric precision of this field. This is meaningless (and set to zero) for non-numeric fields:
Returns the value of the field as a double (float):
Returns the value of the field as an integer:
Returns the value of the field as a string:
Returns the value of the field as a tuple of date and time components:
The Driver class is used internally to wrap an OGR DataSource driver.
Returns the number of OGR vector drivers currently registered.
OGRGeometry objects share similar functionality with GEOSGeometry objects and are thin wrappers around OGR’s internal geometry representation. Thus, they allow for more efficient access to data when using DataSource. Unlike its GEOS counterpart, OGRGeometry supports spatial reference systems and coordinate transformation:
This object is a wrapper for the OGR Geometry class. These objects are instantiated directly from the given geom_input parameter, which may be a string containing WKT, HEX, GeoJSON, a buffer containing WKB data, or an OGRGeomType object. These objects are also returned from the Feature.geom attribute, when reading vector data from Layer (which is in turn a part of a DataSource).
Constructs an OGRGeometry from the given GML string.
Constructs a Polygon from the given bounding-box (a 4-tuple).
Returns the number of points in a LineString, the number of 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, the rings in a Polygon, or the geometries in a GeometryCollection. Not applicable to other geometry types.
Returns the point at the specified index for a LineString, the interior ring at the specified index for a Polygon, or the geometry at the specified index in a GeometryCollection. Not applicable to other geometry types.
Returns the number of coordinated dimensions of the geometry, i.e. 0 for points, 1 for lines, and so forth:
Returns or sets the coordinate dimension of this geometry. For example, the value would be 2 for two-dimensional geometries.
Returns the number of elements in this geometry:
Returns the number of points used to describe this geometry:
Alias for point_count.
Alias for point_count.
Returns the type of this geometry, as an OGRGeomType object.
Returns the name of the type of this geometry:
Returns the area of this geometry, or 0 for geometries that do not contain an area:
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:
This property controls the spatial reference for this geometry, or None if no spatial reference system has been assigned to it. If assigned, accessing this property returns a SpatialReference object. It may be set with another SpatialReference object, or any input that SpatialReference accepts. Example:
Returns or sets the spatial reference identifier corresponding to SpatialReference of this geometry. Returns None if there is no spatial reference information associated with this geometry, or if an SRID cannot be determined.
Returns a GEOSGeometry object corresponding to this geometry.
Returns a string representation of this geometry in GML format:
Returns a string representation of this geometry in HEX WKB format:
Returns a string representation of this geometry in JSON format:
Returns a string representation of this geometry in KML format.
Returns the size of the WKB buffer needed to hold a WKB representation of this geometry:
Returns a buffer containing a WKB representation of this geometry.
Returns a string representation of this geometry in WKT format.
Returns the EWKT representation of this geometry.
Returns a new OGRGeometry clone of this geometry object.
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:
Transforms this geometry to a different spatial reference system. May take a CoordTransform object, a SpatialReference object, or any other input accepted by SpatialReference (including spatial reference WKT and PROJ strings, or an integer SRID).
By default nothing is returned and the geometry is transformed in-place. However, if the clone keyword is set to True then a transformed clone of this geometry is 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 coordinates of a point geometry as a tuple, the coordinates of a line geometry as a tuple of tuples, and so forth:
An alias for tuple.
Returns the X coordinate of this point:
Returns the Y coordinate of this point:
Returns the Z coordinate of this point, or None if the point does not have a Z coordinate:
Returns a list of X coordinates in this line:
Returns a list of Y coordinates in this line:
Returns a list of Z coordinates in this line, or None if the line does not have Z coordinates:
Returns the shell or exterior ring of this polygon, as a LinearRing geometry.
An alias for shell.
Returns a Point representing the centroid of this polygon.
Adds a geometry to this geometry collection. Not applicable to other geometry types.
This class allows for the representation of an OGR geometry type in any of several ways:
Returns a short-hand string form of the OGR Geometry type:
Returns the number corresponding to the OGR geometry type:
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:
Represents an OGR Envelope 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 C 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.
Spatial reference objects are initialized on the given srs_input, which may be one of the following:
Example:
Returns the value of the given string attribute node, None if the node doesn’t exist. Can also take a tuple as a parameter, (target, child), where child is the index of the attribute in the WKT. For example:
The attribute value for the given target node (e.g. 'PROJCS'). The index keyword specifies an index of the child node to return.
Returns the authority name for the given string target node.
Returns the authority code for the given string target node.
Returns a clone of this spatial reference object.
This method inspects the WKT of this SpatialReference and will add EPSG authority nodes where an EPSG identifier is applicable.
Morphs this SpatialReference from ESRI’s format to EPSG
Morphs this SpatialReference to ESRI’s format.
Checks to see if the given spatial reference is valid, if not an exception will be raised.
Import spatial reference from EPSG code.
Import spatial reference from PROJ string.
Import spatial reference from WKT.
Import spatial reference from XML.
Returns the name of this Spatial Reference.
Returns the SRID of top-level authority, or None if undefined.
Returns the name of the linear units.
Returns the value of the linear units.
Returns the name of the angular units.”
Returns the value of the angular units.
Returns a 2-tuple of the units value and the units name and will automatically determines whether to return the linear or angular units.
Returns a tuple of the ellipsoid parameters for this spatial reference: (semimajor axis, semiminor axis, and inverse flattening).
Returns the semi major axis of the ellipsoid for this spatial reference.
Returns the semi minor axis of the ellipsoid for this spatial reference.
Returns the inverse flattening of the ellipsoid for this spatial reference.
Returns True if this spatial reference is geographic (root node is GEOGCS).
Returns True if this spatial reference is local (root node is LOCAL_CS).
Returns True if this spatial reference is a projected coordinate system (root node is PROJCS).
Returns the WKT representation of this spatial reference.
Returns the ‘pretty’ representation of the WKT.
Returns the PROJ representation for this spatial reference.
Alias for SpatialReference.proj.
Returns the XML representation of this spatial reference.
Represents a coordinate system transform. It is initialized with two SpatialReference, representing the source and target coordinate systems, respectively. These objects should be used when performing the same coordinate transformation repeatedly on different geometries:
GDALRaster is a wrapper for the GDAL raster source object that supports reading data from a variety of GDAL-supported geospatial file formats and data sources using a consistent interface. Each data source is represented by a GDALRaster object which contains one or more layers of data named bands. Each band, represented by a GDALBand object, contains georeferenced image data. For example, an RGB image is represented as three bands: one for red, one for green, and one for blue.
Note
For raster data there is no difference between a raster instance and its data source. Unlike for the Geometry objects, GDALRaster objects are always a data source. Temporary rasters can be instantiated in memory using the corresponding driver, but they will be of the same class as file-based raster sources.
The constructor for GDALRaster accepts two parameters. The first parameter defines the raster source, and the second parameter defines if a raster should be opened in write mode. For newly-created rasters, the second parameter is ignored and the new raster is always created in write mode.
The first parameter can take three forms: a string representing a file path (filesystem or GDAL virtual filesystem), a dictionary with values defining a new raster, or a bytes object representing a raster file.
If the input is a file path, the raster is opened from there. If the input is raw data in a dictionary, the parameters width, height, and srid are required. If the input is a bytes object, it will be opened using a GDAL virtual filesystem.
For a detailed description of how to create rasters using dictionary input, see Creating rasters from data. For a detailed description of how to create rasters in the virtual filesystem, see Using GDAL’s Virtual Filesystem.
The following example shows how rasters can be created from different input sources (using the sample data from the GeoDjango tests; see also the Sample Data section).
Creating rasters in any GDAL virtual filesystem was allowed.
The name of the source which is equivalent to the input file path or the name provided upon instantiation.
The name of the GDAL driver used to handle the input file. For GDALRasters created from a file, the driver type is detected automatically. The creation of rasters from scratch is an in-memory raster by default ('MEM'), but can be altered as needed. For instance, use GTiff for a GeoTiff file. For a list of file types, see also the GDAL Raster Formats list.
An in-memory raster is created through the following example:
A file based GeoTiff raster is created through the following example:
The width of the source in pixels (X-axis).
The height of the source in pixels (Y-axis).
The spatial reference system of the raster, as a SpatialReference instance. The SRS can be changed by setting it to an other SpatialReference or providing any input that is accepted by the SpatialReference constructor.
The Spatial Reference System Identifier (SRID) of the raster. This property is a shortcut to getting or setting the SRID through the srs attribute.
The affine transformation matrix used to georeference the source, as a tuple of six coefficients which map pixel/line coordinates into georeferenced space using the following relationship:
The same values can be retrieved by accessing the origin (indices 0 and 3), scale (indices 1 and 5) and skew (indices 2 and 4) properties.
The default is [0.0, 1.0, 0.0, 0.0, 0.0, -1.0].
Coordinates of the top left origin of the raster in the spatial reference system of the source, as a point object with x and y members.
Pixel width and height used for georeferencing the raster, as a point object with x and y members. See geotransform for more information.
Skew coefficients used to georeference the raster, as a point object with x and y members. In case of north up images, these coefficients are both 0.
Extent (boundary values) of the raster source, as a 4-tuple (xmin, ymin, xmax, ymax) in the spatial reference system of the source.
List of all bands of the source, as GDALBand instances.
Returns a warped version of this raster.
The warping parameters can be specified through the ds_input argument. The use of ds_input is analogous to the corresponding argument of the class constructor. It is a dictionary with the characteristics of the target raster. Allowed dictionary key values are width, height, SRID, origin, scale, skew, datatype, driver, and name (filename).
By default, the warp functions keeps most parameters equal to the values of the original source raster, so only parameters that should be changed need to be specified. Note that this includes the driver, so for file-based rasters the warp function will create a new raster on disk.
The only parameter that is set differently from the source raster is the name. The default value of the raster name is the name of the source raster appended with '_copy' + source_driver_name. For file-based rasters it is recommended to provide the file path of the target raster.
The resampling algorithm used for warping can be specified with the resampling argument. The default is NearestNeighbor, and the other allowed values are Bilinear, Cubic, CubicSpline, Lanczos, Average, and Mode.
The max_error argument can be used to specify the maximum error measured in input pixels that is allowed in approximating the transformation. The default is 0.0 for exact calculations.
For users familiar with GDAL, this function has a similar functionality to the gdalwarp command-line utility.
For example, the warp function can be used for aggregating a raster to the double of its original pixel scale:
Transforms this raster to a different spatial reference system (srs), which may be a SpatialReference object, or any other input accepted by SpatialReference (including spatial reference WKT and PROJ strings, or an integer SRID).
It calculates the bounds and scale of the current raster in the new spatial reference system and warps the raster using the warp function.
By default, the driver of the source raster is used and the name of the raster is the original name appended with '_copy' + source_driver_name. A different driver or name can be specified with the driver and name arguments.
The default resampling algorithm is NearestNeighbour but can be changed using the resampling argument. The default maximum allowed error for resampling is 0.0 and can be changed using the max_error argument. Consult the warp documentation for detail on those arguments.
Support for SpatialReference srs was added
Returns a string with a summary of the raster. This is equivalent to the gdalinfo command line utility.
The metadata of this raster, represented as a nested dictionary. The first-level key is the metadata domain. The second-level contains the metadata item names and values from each domain.
To set or update a metadata item, pass the corresponding metadata item to the method using the nested structure described above. Only keys that are in the specified dictionary are updated; the rest of the metadata remains unchanged.
To remove a metadata item, use None as the metadata value.
A bytes representation of this raster. Returns None for rasters that are not stored in GDAL’s virtual filesystem.
A boolean indicating if this raster is stored in GDAL’s virtual filesystem.
GDALBand instances are not created explicitly, but rather obtained from a GDALRaster object, through its bands attribute. The GDALBands contain the actual pixel values of the raster.
The name or description of the band, if any.
The width of the band in pixels (X-axis).
The height of the band in pixels (Y-axis).
The total number of pixels in this band. Is equal to width * height.
Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation).
If the approximate argument is set to True, the statistics may be computed based on overviews or a subset of image tiles.
If the refresh argument is set to True, the statistics will be computed from the data directly, and the cache will be updated with the result.
If a persistent cache value is found, that value is returned. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file. In some cases this metadata might be out of sync with the pixel values or cause values from a previous call to be returned which don’t reflect the value of the approximate argument. In such cases, use the refresh argument to get updated values and store them in the cache.
For empty bands (where all pixel values are “no data”), all statistics are returned as None.
The statistics can also be retrieved directly by accessing the min, max, mean, and std properties.
The minimum pixel value of the band (excluding the “no data” value).
The maximum pixel value of the band (excluding the “no data” value).
The mean of all pixel values of the band (excluding the “no data” value).
The standard deviation of all pixel values of the band (excluding the “no data” value).
The “no data” value for a band is generally a special marker value used to mark pixels that are not valid data. Such pixels should generally not be displayed, nor contribute to analysis operations.
To delete an existing “no data” value, set this property to None (requires GDAL ≥ 2.1).
The data type contained in the band, as an integer constant between 0 (Unknown) and 11. If as_string is True, the data type is returned as a string with the following possible values: GDT_Unknown, GDT_Byte, GDT_UInt16, GDT_Int16, GDT_UInt32, GDT_Int32, GDT_Float32, GDT_Float64, GDT_CInt16, GDT_CInt32, GDT_CFloat32, and GDT_CFloat64.
The color interpretation for the band, as an integer between 0and 16. If as_string is True, the data type is returned as a string with the following possible values: GCI_Undefined, GCI_GrayIndex, GCI_PaletteIndex, GCI_RedBand, GCI_GreenBand, GCI_BlueBand, GCI_AlphaBand, GCI_HueBand, GCI_SaturationBand, GCI_LightnessBand, GCI_CyanBand, GCI_MagentaBand, GCI_YellowBand, GCI_BlackBand, GCI_YCbCr_YBand, GCI_YCbCr_CbBand, and GCI_YCbCr_CrBand. GCI_YCbCr_CrBand also represents GCI_Max because both correspond to the integer 16, but only GCI_YCbCr_CrBand is returned as a string.
The accessor to the pixel values of the GDALBand. Returns the complete data array if no parameters are provided. A subset of the pixel array can be requested by specifying an offset and block size as tuples.
If NumPy is available, the data is returned as NumPy array. For performance reasons, it is highly recommended to use NumPy.
Data is written to the GDALBand if the data parameter is provided. The input can be of one of the following types - packed string, buffer, list, array, and NumPy array. The number of items in the input should normally correspond to the total number of pixels in the band, or to the number of pixels for a specific block of pixel values if the offset and size parameters are provided.
If the number of items in the input is different from the target pixel block, the shape parameter must be specified. The shape is a tuple that specifies the width and height of the input data in pixels. The data is then replicated to update the pixel values of the selected block. This is useful to fill an entire band with a single value, for instance.
For example:
The metadata of this band. The functionality is identical to GDALRaster.metadata.
This section describes how to create rasters from scratch using the ds_input parameter.
A new raster is created when a dict is passed to the GDALRaster constructor. The dictionary contains defining parameters of the new raster, such as the origin, size, or spatial reference system. The dictionary can also contain pixel data and information about the format of the new raster. The resulting raster can therefore be file-based or memory-based, depending on the driver specified.
There’s no standard for describing raster data in a dictionary or JSON flavor. The definition of the dictionary input to the GDALRaster class is therefore specific to Django. It’s inspired by the geojson format, but the geojson standard is currently limited to vector formats.
Examples of using the different keys when creating rasters can be found in the documentation of the corresponding attributes and methods of the GDALRaster and GDALBand classes.
Only a few keys are required in the ds_input dictionary to create a raster: width, height, and srid. All other parameters have default values (see the table below). The list of keys that can be passed in the ds_input dictionary is closely related but not identical to the GDALRaster properties. Many of the parameters are mapped directly to those properties; the others are described below.
The following table describes all keys that can be set in the ds_input dictionary.
String representing the name of the raster. When creating a file-based raster, this parameter must be the file path for the new raster. If the name starts with /vsimem/, the raster is created in GDAL’s virtual filesystem.
Integer representing the data type for all the bands. Defaults to 6 (Float32). All bands of a new raster are required to have the same datatype. The value mapping is:
Integer representing the number of bands of the raster. A raster can be created without passing band data upon creation. If the number of bands isn’t specified, it’s automatically calculated from the length of the bands input. The number of bands can’t be changed after creation.
A list of band_input dictionaries with band input data. The resulting band indices are the same as in the list provided. The definition of the band input dictionary is given below. If band data isn’t provided, the raster bands values are instantiated as an array of zeros and the “no data” value is set to None.
A dictionary with raster creation options. The key-value pairs of the input dictionary are passed to the driver on creation of the raster.
The available options are driver-specific and are described in the documentation of each driver.
The values in the dictionary are not case-sensitive and are automatically converted to the correct string format upon creation.
The following example uses some of the options available for the GTiff driver. The result is a compressed signed byte raster with an internal tiling scheme. The internal tiles have a block size of 23 by 23:
The bands key in the ds_input dictionary is a list of band_input dictionaries. Each band_input dictionary can contain pixel values and the “no data” value to be set on the bands of the new raster. The data array can have the full size of the new raster or be smaller. For arrays that are smaller than the full raster, the size, shape, and offset keys control the pixel values. The corresponding keys are passed to the data() method. Their functionality is the same as setting the band data with that method. The following table describes the keys that can be used.
GDAL can access files stored in the filesystem, but also supports virtual filesystems to abstract accessing other kind of files, such as compressed, encrypted, or remote files.
GDAL has an internal memory-based filesystem, which allows treating blocks of memory as files. It can be used to read and write GDALRaster objects to and from binary file buffers.
This is useful in web contexts where rasters might be obtained as a buffer from a remote storage or returned from a view without being written to disk.
GDALRaster objects are created in the virtual filesystem when a bytes object is provided as input, or when the file path starts with /vsimem/.
Input provided as bytes has to be a full binary representation of a file. For instance:
To create a new virtual file-based raster from scratch, use the ds_input dictionary representation and provide a name argument that starts with /vsimem/ (for detail of the dictionary representation, see Creating rasters from data). For virtual file-based rasters, the vsi_buffer attribute returns the bytes representation of the raster.
Here’s how to create a raster and return it as a file in an HttpResponse:
Depending on the local build of GDAL other virtual filesystems may be supported. You can use them by prepending the provided path with the appropriate /vsi*/ prefix. See the GDAL Virtual Filesystems documentation for more details.
Instead decompressing the file and instantiating the resulting raster, GDAL can directly access compressed files using the /vsizip/, /vsigzip/, or /vsitar/ virtual filesystems:
GDAL can support online resources and storage providers transparently. As long as it’s built with such capabilities.
To access a public raster file with no authentication, you can use /vsicurl/:
For commercial storage providers (e.g. /vsis3/) the system should be previously configured for authentication and possibly other settings (see the GDAL Virtual Filesystems documentation for available options).
A string specifying the location of the GDAL library. Typically, this setting is only used if the GDAL library is in a non-standard location (e.g., /home/john/lib/libgdal.so).
The base GDAL exception, indicating a GDAL-related error.
An exception raised when an error occurs when constructing or using a spatial reference system object.


The GeoIP2 object is a wrapper for the MaxMind geoip2 Python library. [1]
In order to perform IP-based geolocation, the GeoIP2 object requires the geoip2 Python library and the GeoIP Country and/or City datasets in binary format (the CSV files will not work!). Grab the GeoLite2-Country.mmdb.gz and GeoLite2-City.mmdb.gz files and unzip them in a directory corresponding to the GEOIP_PATH setting.
Additionally, it is recommended to install the libmaxminddb C library, so that geoip2 can leverage the C library’s faster speed.
Here is an example of its usage:
The GeoIP object does not require any parameters to use the default settings. However, at the very least the GEOIP_PATH setting should be set with the path of the location of your GeoIP datasets. The following initialization keywords may be used to customize any of the defaults.
This classmethod instantiates the GeoIP object from the given database path and given cache setting.
All the following querying routines may take either a string IP address or a fully qualified domain name (FQDN). For example, both '205.186.163.125' and 'djangoproject.com' would be valid query parameters.
Returns a dictionary of city information for the given query. Some of the values in the dictionary may be undefined (None).
Returns a dictionary with the country code and country for the given query.
Returns the country code corresponding to the query.
Returns the country name corresponding to the query.
Returns a coordinate tuple of (longitude, latitude).
Returns a coordinate tuple of (longitude, latitude).
Returns a coordinate tuple of (latitude, longitude),
Returns a Point object corresponding to the query.
A string or pathlib.Path specifying the directory where the GeoIP data files are located. This setting is required unless manually specified with path keyword when initializing the GeoIP2 object.
The basename to use for the GeoIP country data file. Defaults to 'GeoLite2-Country.mmdb'.
The basename to use for the GeoIP city data file. Defaults to 'GeoLite2-City.mmdb'.
The exception raised when an error occurs in a call to the underlying geoip2 library.


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 high-level Python wrapper for the GEOS library, its features include:
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:
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:
All these constructors take the keyword argument srid. For example:
Finally, there is the fromfile() factory method which returns a GEOSGeometry object from a file:
My logs are filled with GEOS-related errors
You find many TypeError or AttributeError exceptions filling your web server’s log files. This generally means that you are creating GEOS objects at the top level of some of your Python modules. Then, due to a race condition in the garbage collector, your module is garbage collected before the GEOS object. To prevent this, create GEOSGeometry objects inside the local scope of your functions/methods.
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:
With any geometry object, the GEOSGeometry.coords property may be used to get the geometry coordinates as a Python tuple:
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:
Whereas indexing on a Polygon will return the ring (a LinearRing object) corresponding to the index:
In addition, coordinates/components of the geometry may added or modified, just like a Python list:
Geometries support set-like operators:
Equality operator doesn’t check spatial equality
The GEOSGeometry equality operator uses equals_exact(), not equals(), i.e. it requires the compared geometries to have the same coordinates in the same positions with the same SRIDs:
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 srid parameter, if given, is set as the SRID of the created geometry if geo_input doesn’t have an SRID. If different SRIDs are provided through the geo_input and srid parameters, ValueError is raised:
The following input formats, along with their corresponding Python types, are accepted:
For the GeoJSON format, the SRID is set based on the crs member. If crs isn’t provided, the SRID defaults to 4326.
Constructs a GEOSGeometry from the given GML string.
Returns the coordinates of the geometry as a tuple.
Returns the dimension of the geometry:
Returns whether or not the set of points in the geometry is empty.
Returns a string corresponding to the type of geometry. For example:
Returns the GEOS geometry type identification number. The following table shows the value for each geometry type:
Returns the number of coordinates in the geometry.
Returns the number of geometries in this geometry. In other words, will return 1 on anything but geometry collections.
Returns a boolean indicating whether the geometry is three-dimensional.
Returns a boolean indicating whether the geometry is a LinearRing.
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 Polygon objects are always simple because they do cannot intersect themselves, by definition.
Returns a boolean indicating whether the geometry is valid.
Returns a string describing the reason why a geometry is invalid.
Property that may be used to retrieve or set the SRID associated with the geometry. For example:
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.
Returns the “extended” Well-Known Text of the geometry. This representation is specific to PostGIS and is a superset 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.
Returns the WKB of this Geometry in hexadecimal form. Please note that the SRID value is not included in this representation because it is not a part of the OGC specification (use the GEOSGeometry.hexewkb property instead).
Returns the EWKB of this Geometry in hexadecimal form. This is an extension of the WKB specification that includes the SRID value that are a part of this geometry.
Returns the GeoJSON representation of the geometry. Note that the result is not a complete GeoJSON structure but only the geometry key content of a GeoJSON structure. See also GeoJSON Serializer.
Alias for GEOSGeometry.json.
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.
Returns an OGRGeometry object corresponding to the GEOS geometry.
Returns the WKB (Well-Known Binary) representation of this Geometry as a Python buffer. SRID value is not included, use the GEOSGeometry.ewkb property instead.
Return the EWKB representation of this Geometry as a Python buffer. This is an extension of the WKB specification that includes any SRID value that are a part of this geometry.
Returns the Well-Known 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.
Returns True if other.within(this) returns True.
Returns True if this geometry covers the specified geometry.
The covers predicate has the following equivalent definitions:
If either geometry is empty, returns False.
This predicate is similar to GEOSGeometry.contains(), but is more inclusive (i.e. returns True for more cases). In particular, unlike contains() it does not distinguish between points in the boundary and in the interior of geometries. For most situations, covers() should be preferred to contains(). As an added benefit, covers() is more amenable to optimization and hence should outperform contains().
Returns True if the DE-9IM 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).
Returns True if the DE-9IM intersection matrix for the two geometries is FF*FF****.
Returns True if the DE-9IM intersection matrix for the two geometries is T*F**FFF*.
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.
Returns True if GEOSGeometry.disjoint() is False.
Returns true if the DE-9IM intersection matrix for the two geometries is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves).
Returns True if the elements in the DE-9IM intersection matrix for this geometry and the other matches the given pattern – a string of nine characters from the alphabet: {T, F, *, 0}.
Returns True if the DE-9IM intersection matrix for the two geometries is FT*******, F**T***** or F***T****.
Returns True if the DE-9IM intersection matrix for the two geometries is T*F**F***.
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).
Same as buffer(), but allows customizing the style of the buffer.
Returns a GEOSGeometry representing the points making up this geometry that do not make up other.
Given a distance (float), returns the point (or closest point) within the geometry (LineString or MultiLineString) at that distance. The normalized version takes the distance as a float between 0 (origin) and 1 (endpoint).
Reverse of GEOSGeometry.project().
Returns a GEOSGeometry representing the points shared by this geometry and other.
Returns the distance (float) from the origin of the geometry (LineString or MultiLineString) to the point projected on the geometry (that is to a point of the line the closest to the given point). The normalized version returns the distance as a float between 0 (origin) and 1 (endpoint).
Reverse of GEOSGeometry.interpolate().
Returns the DE-9IM intersection matrix (a string) representing the topological relationship between this geometry and the other.
Returns a new GEOSGeometry, simplified to the specified tolerance using the Douglas-Peucker algorithm. A higher tolerance value implies fewer points in the output. If no tolerance is provided, it defaults to 0.
By default, this function does not preserve topology. For example, Polygon objects can be split, be collapsed into lines, or disappear. Polygon holes can be created or disappear, and lines may cross. By specifying preserve_topology=True, the result will have the same dimension and number of components as the input; this is significantly slower, however.
Returns a GEOSGeometry combining the points in this geometry not in other, and the points in other not in this geometry.
Returns a GEOSGeometry representing all the points in this geometry and the other.
Returns the boundary as a newly allocated Geometry object.
Returns a Point object representing the geometric center of the geometry. The point is not guaranteed to be on the interior of the geometry.
Returns the smallest Polygon that contains all the points in the geometry.
Returns a Polygon that represents the bounding envelope of this geometry. Note that it can also return a Point if the input geometry is a point.
Computes and returns a Point guaranteed to be on the interior of this geometry.
Computes the union of all the elements of this geometry.
The result obeys the following contract:
This property returns the area of the Geometry.
This property returns the extent of this geometry as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).
This method returns a GEOSGeometry that is a clone of the original.
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.
Returns the length of this geometry (e.g., 0 for a Point, the length of a LineString, or the circumference of a Polygon).
Returns a GEOS PreparedGeometry for the contents of this geometry. PreparedGeometry objects are optimized for the contains, intersects, covers, crosses, disjoint, overlaps, touches and within operations. Refer to the Prepared Geometries documentation for more information.
Returns a SpatialReference object corresponding to the SRID of the geometry or None.
Transforms the geometry according to the given coordinate transformation parameter (ct), which may be an integer SRID, spatial reference WKT string, a PROJ string, a SpatialReference object, or a CoordTransform object. By default, the geometry is transformed in-place 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
Raises GEOSException if GDAL is not available or if the geometry’s SRID is None or less than 0. It doesn’t impose any constraints on the geometry’s SRID if called with a CoordTransform object.
Converts this geometry to canonical form:
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:
Empty Point objects may be instantiated by passing no arguments or an empty sequence. The following are equivalent:
LineString objects are instantiated using arguments that are either a sequence of coordinates or Point objects. For example, the following are equivalent:
In addition, LineString objects may also be created by passing in a single sequence of coordinate or Point objects:
Empty LineString objects may be instantiated by passing no arguments or an empty sequence. The following are equivalent:
Returns whether or not this LineString is closed.
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:
Notice that (0, 0) is the first and last coordinate – if they were not equal, an error would be raised.
Returns whether this LinearRing is counterclockwise.
Polygon objects may be instantiated by passing in 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:
Returns a polygon object from the given bounding-box, a 4-tuple comprising (xmin, ymin, xmax, ymax).
Returns the number of interior rings in this geometry.
Comparing Polygons
Note that it is possible to compare Polygon objects directly with < or >, but as the comparison is made through Polygon’s LineString, it does not mean much (but is consistent and quick). You can always force the comparison with the area property:
MultiPoint objects may be instantiated by passing in Point objects as arguments, or a single sequence of Point objects:
MultiLineString objects may be instantiated by passing in LineString objects as arguments, or a single sequence of LineString objects:
Returns a LineString representing the line merge of all the components in this MultiLineString.
Returns True if and only if all elements are closed.
MultiPolygon objects may be instantiated by passing Polygon objects as arguments, or a single sequence of Polygon objects:
GeometryCollection objects may be instantiated by passing in other GEOSGeometry as arguments, or a single sequence of GEOSGeometry objects:
In order to obtain a prepared geometry, 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.
For example:
All methods on PreparedGeometry take an other argument, which must be a GEOSGeometry instance.
Example:
a GEOSGeometry corresponding to the spatial data in the string
fromstr(string, srid) is equivalent to GEOSGeometry(string, srid).
Example:
The reader I/O classes return a GEOSGeometry instance from the WKB and/or WKT input given to their read(geom) method.
Example:
Example:
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 value (in other words, EWKB).
WKBWriter provides the most control over its output. By default it returns OGC-compliant WKB when its 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. See the WKBWriter.outdim documentation for more details about the dim argument.
Returns the WKB of the given geometry as a Python buffer object. Example:
Returns WKB of the geometry in hexadecimal. Example:
This property may be set to change the byte-order of the geometry representation.
Example:
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.
Example:
Set this property with a boolean to indicate whether the SRID of the geometry should be included with the WKB representation. Example:
This class allows outputting the WKT representation of a geometry. See the WKBWriter.outdim, trim, and precision attributes for details about the constructor arguments.
Returns the WKT of the given geometry. Example:
See WKBWriter.outdim.
This property is used to enable or disable trimming of unnecessary decimals.
This property controls the rounding precision of coordinates; if set to None rounding is disabled.
A string specifying the location of the GEOS C library. Typically, this setting is only used if the GEOS C library is in a non-standard 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.
The base GEOS exception, indicates a GEOS-related error.