Vector API

This page contains classes, methods, functions that relate to the GDAL Vector Data Model. The Driver and Dataset classes, which applies to both vector and raster data, are documented with the Raster API.

Layer

class osgeo.ogr.Layer(*args, **kwargs)

Proxy of C++ OGRLayerShadow class.

AlterFieldDefn(self, iField, field_def, nFlags) OGRErr

Alter the definition of an existing field on a layer.

For more details: OGR_L_AlterFieldDefn()

Parameters:
  • iField (int) -- index of the field whose definition must be altered.

  • field_def (FieldDefn) -- new field definition

  • nFlags (int) -- Combination of osgeo.ogr.ALTER_NAME_FLAG, osgeo.ogr.ALTER_TYPE_FLAG, osgeo.ogr.ALTER_WIDTH_PRECISION_FLAG, osgeo.ogr.ALTER_NULLABLE_FLAG and osgeo.ogr.ALTER_DEFAULT_FLAG to indicate which of the name and/or type and/or width and precision fields and/or nullability from the new field definition must be taken into account.

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

AlterGeomFieldDefn(self, iGeomField, field_def, nFlags) OGRErr
Clip(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Clip off areas that are not covered by the method layer.

For more details: OGR_L_Clip()

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

CommitTransaction(self) OGRErr

For datasources which support transactions, this commits a transaction.

For more details: OGR_L_CommitTransaction()

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

CreateFeature(self, feature) OGRErr

Create and write a new feature within a layer.

For more details: OGR_L_CreateFeature()

To create a feature, but set it if it exists see Layer.UpsertFeature().

Parameters:

feature (Feature) -- The feature to write to disk.

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

CreateField(self, field_def, approx_ok=1) OGRErr

Create a new field on a layer.

For more details: OGR_L_CreateField()

Parameters:
  • field_def (FieldDefn) -- The field definition to write to disk.

  • approx_ok (bool, default=True) -- If True, the field may be created in a slightly different form depending on the limitations of the format driver.

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

CreateFieldFromArrowSchema(self, schema, options=None) OGRErr
CreateFieldFromPyArrowSchema(pa_schema, options=[])

Create a field from the passed pyarrow Schema.

CreateFields(fields)

Create a list of fields on the Layer

CreateGeomField(self, field_def, approx_ok=1) OGRErr

Create a new geometry field on a layer.

For more details: OGR_L_CreateGeomField()

Parameters:
  • field_def (GeomFieldDefn) -- The geometry field definition to write to disk.

  • approx_ok (bool, default=True) -- If True, the field may be created in a slightly different form depending on the limitations of the format driver.

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

DeleteFeature(self, fid) OGRErr

Delete feature from layer.

For more details: OGR_L_DeleteFeature()

Parameters:

fid (int) -- The feature id to be deleted from the layer

Returns:

osgeo.ogr.OGRERR_NONE if the operation works, otherwise an appropriate error code (e.g osgeo.ogr.OGRERR_NON_EXISTING_FEATURE) if the feature does not exist.

Return type:

int

DeleteField(self, iField) OGRErr

Delete an existing field on a layer.

For more details: OGR_L_DeleteField()

Parameters:

iField (int) -- index of the field to delete.

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

Dereference()

For backwards compatibility only.

Erase(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Remove areas that are covered by the method layer.

For more details: OGR_L_Erase()

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

ExportArrowArrayStreamPyCapsule(self, options=None) PyObject *
FindFieldIndex(self, pszFieldName, bExactMatch) int

Find the index of field in a layer.

For more details: OGR_L_FindFieldIndex()

Returns:

field index, or -1 if the field doesn't exist

Return type:

int

GetArrowArrayStreamInterface(options=[])

Return a proxy object that implements the __arrow_c_stream__() method, but allows the user to pass options.

Parameters:

options (list of str or dict, optional) -- Options such as INCLUDE_FID=NO, MAX_FEATURES_IN_BATCH=<number>, etc.

Returns:

A proxy object that implements the __arrow_c_stream__() method.

Return type:

object

GetArrowStream(self, options=None) ArrowArrayStream
GetArrowStreamAsNumPy(options=[])

Return an ArrowStream as NumPy Array objects. A specific option to this method is USE_MASKED_ARRAYS=YES/NO (default is YES).

GetArrowStreamAsPyArrow(options=[])

Return an ArrowStream as PyArrow Schema and Array objects

GetAttributeFilter(self) char const *
GetDataset(self) GDALDatasetShadow *

Return the dataset associated with this layer.

For more details: OGR_L_GetDataset()

Returns:

A dataset if successful, or None on failure.

Return type:

Dataset or None

GetExtent(self, force=1, can_return_null=0, geom_field=0)

Fetch the extent of this layer.

For more details:

Warning

Check the return order of the bounds.

Parameters:
  • force (int, default=False) -- Flag indicating whether the extent should be computed even if it is expensive.

  • can_return_null (int, default=False) -- Whether None can be returned in the response.

  • geom_field (int, default=0) -- The index of the geometry field on which to compute the extent. Can be iterated over using range() and GetGeomFieldCount().

Returns:

(minx, maxx, miny, maxy)

Return type:

tuple of float

GetExtent3D(self, force=1, can_return_null=0, geom_field=0)
GetFIDColumn(self) char const *

This method returns the name of the underlying database column being used as the FID column, or '' if not supported.

For more details: OGR_L_GetFIDColumn()

Returns:

fid column name.

Return type:

str

GetFeature(self, fid) Feature

Fetch a feature by its identifier.

For more details: OGR_L_GetFeature()

Use TestCapability() with (osgeo.ogr.OLCRandomRead) to establish if this layer supports efficient random access reading via GetFeature(); However, the call should always work if the feature exists.

Sequential reads (with GetNextFeature()) are generally considered interrupted by a GetFeature() call.

Parameters:

fid (int) -- The feature id of the feature to read.

Returns:

A new feature now owned by the caller, or None on failure. The returned feature should be deleted with Destroy().

Return type:

Feature

GetFeatureCount(self, force=1) GIntBig

Fetch the feature count in this layer.

For more details: OGR_L_GetFeatureCount()

Parameters:

force (int) -- Flag indicating whether the count should be computed even if it is expensive.

Returns:

Feature count, -1 if count not known.

Return type:

int

GetFeaturesRead(self) GIntBig

For more details: OGR_L_GetFeaturesRead()

GetGeomType(self) OGRwkbGeometryType

Return the layer geometry type.

For more details: OGR_L_GetGeomType()

Returns:

The geometry type code. The types can be found with 'osgeo.ogr.wkb' prefix. For example osgeo.ogr.wkbPolygon.

Return type:

int

GetGeometryColumn(self) char const *

This method returns the name of the underlying database column being used as the geometry column, or '' if not supported.

For more details: OGR_L_GetGeometryColumn()

Returns:

geometry column name.

Return type:

str

GetGeometryTypes(self, geom_field=0, flags=0, callback=0, callback_data=None)

Get actual geometry types found in features.

For more details: OGR_L_GetGeometryTypes()

Parameters:
  • geom_field (int, optional) -- index of the geometry field

  • flags (int, optional) -- 0, or a combination of osgeo.ogr.GGT_COUNT_NOT_NEEDED, osgeo.ogr.GGT_STOP_IF_MIXED and osgeo.ogr.GGT_GEOMCOLLECTIONZ_TINZ

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for cancellation or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

A dictionary whose keys are osgeo.ogr.wkbXXXX constants and values the corresponding number of geometries of that type in the layer.

Return type:

dict

GetLayerDefn(self) FeatureDefn

Fetch the schema information for this layer.

For more details: OGR_L_GetLayerDefn()

Returns:

The feature definition.

Return type:

FeatureDefn

GetName(self) char const *

Return the layer name.

For more details: OGR_L_GetName()

Returns:

The layer name

Return type:

str

GetNextFeature(self) Feature

Fetch the next available feature from this layer.

For more details: OGR_L_GetNextFeature()

Returns:

A feature or None if no more features are available.

Return type:

Feature

GetRefCount(self) int

For more details: OGR_L_GetRefCount()

GetSpatialFilter(self) Geometry

This function returns the current spatial filter for this layer.

For more details: OGR_L_GetSpatialFilter()

Returns:

The spatial filter geometry.

Return type:

Geometry

GetSpatialRef(self) SpatialReference

Fetch the spatial reference system for this layer.

For more details: OGR_L_GetSpatialRef()

Returns:

spatial reference, or None if there isn't one.

Return type:

SpatialReference

GetStyleTable(self) StyleTable

Get style table.

For more details: OGR_L_GetStyleTable()

GetSupportedSRSList(self, geom_field=0)
Identity(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Identify the features of this layer with the ones from the identity layer.

For more details: OGR_L_Identity()

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

Intersection(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Intersection of two layers.

For more details: OGR_L_Intersection()

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

IsArrowSchemaSupported(self, schema, options=None)
IsPyArrowSchemaSupported(pa_schema, options=[])

Returns whether the passed pyarrow Schema is supported by the layer, as a tuple (success: bool, errorMsg: str).

This may be used as a preliminary check before calling WritePyArrowBatch()

Reference()

For backwards compatibility only.

Rename(self, new_name) OGRErr
ReorderField(self, iOldFieldPos, iNewFieldPos) OGRErr

Reorder an existing field on a layer.

For more details: OGR_L_ReorderField()

Parameters:
  • iOldFieldPos (int) -- previous position of the field to move. Must be in the range [0,GetFieldCount()-1].

  • iNewFieldPos (int) -- new position of the field to move. Must be in the range [0,GetFieldCount()-1].

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

ReorderFields(self, nList) OGRErr

Reorder all the fields of a layer.

For more details: OGR_L_ReorderFields()

Parameters:

nList (list[int]) -- A list of GetLayerDefn().GetFieldCount() elements which is a permutation of [0, GetLayerDefn().GetFieldCount()-1].

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

ResetReading(self)

Reset feature reading to start on the first feature.

For more details: OGR_L_ResetReading()

RollbackTransaction(self) OGRErr

Roll back a datasource to its state before the start of the current transaction.

For more details: OGR_L_RollbackTransaction()

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

SetActiveSRS(self, geom_field, srs) OGRErr
SetAttributeFilter(self, filter_string) OGRErr

Set a new attribute query.

For more details: OGR_L_SetAttributeFilter()

Parameters:

filter_string (str) -- query in restricted SQL WHERE format, or None to clear the current query.

Returns:

osgeo.ogr.OGRERR_NONE if successfully installed, or an error code if the query expression is in error, or some other failure occurs.

Return type:

int

SetFeature(self, feature) OGRErr

Rewrite an existing feature.

For more details: OGR_L_SetFeature()

To set a feature, but create it if it doesn't exist see Layer.UpsertFeature().

Parameters:

feature (Feature) -- The feature to write.

Returns:

osgeo.ogr.OGRERR_NONE if the operation works, otherwise an appropriate error code (e.g osgeo.ogr.OGRERR_NON_EXISTING_FEATURE if the feature does not exist).

Return type:

int

SetIgnoredFields(self, options) OGRErr

Set which fields can be omitted when retrieving features from the layer.

For more details: OGR_L_SetIgnoredFields()

Parameters:

options (list[str]) -- A list of field names. If an empty list is passed, the ignored list is cleared.

Returns:

osgeo.ogr.OGRERR_NONE if all field names have been resolved (even if the driver does not support this method)

Return type:

int

SetNextByIndex(self, new_index) OGRErr

Move read cursor to the nIndex'th feature in the current resultset.

For more details: OGR_L_SetNextByIndex()

Parameters:

new_index (int) -- The index indicating how many steps into the result set to seek.

Returns:

osgeo.ogr.OGRERR_NONE on success or an error code.

Return type:

int

SetSpatialFilter(self, filter)
SetSpatialFilter(self, iGeomField, filter) None

Set a new spatial filter.

For more details:

Parameters:
  • iGeomField (int, optional) -- index of the geometry field on which the spatial filter operates.

  • filter (Geometry) -- The geometry to use as a filtering region. None may be passed indicating that the current spatial filter should be cleared, but no new one instituted.

SetSpatialFilterRect(self, minx, miny, maxx, maxy)
SetSpatialFilterRect(self, iGeomField, minx, miny, maxx, maxy) None

Set a new rectangular spatial filter.

For more details:

Parameters:
  • iGeomField (int, optional) -- index of the geometry field on which the spatial filter operates.

  • minx (float) -- the minimum X coordinate for the rectangular region.

  • miny (float) -- the minimum Y coordinate for the rectangular region.

  • maxx (float) -- the maximum X coordinate for the rectangular region.

  • maxy (float) -- the maximum Y coordinate for the rectangular region.

SetStyleTable(self, table)

Set style table.

For more details: OGR_L_SetStyleTable()

StartTransaction(self) OGRErr

For datasources which support transactions, this creates a transaction.

For more details: OGR_L_StartTransaction()

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

SymDifference(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Symmetrical difference of two layers.

For more details: OGR_L_SymDifference()

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

SyncToDisk(self) OGRErr

Flush pending changes to disk.

For more details: OGR_L_SyncToDisk()

Returns:

osgeo.ogr.OGRERR_NONE if no error occurs (even if nothing is done) or an error code.

Return type:

int

TestCapability(self, cap) bool

Test if this layer supported the named capability.

For more details: OGR_L_TestCapability()

Parameters:

cap (str) -- The name of the capability to test. These can be found in the osgeo.ogr namespace. For example, osgeo.ogr.OLCRandomRead.

Returns:

True if the layer has the requested capability, or False otherwise. Will return False for any unrecognized capabilities.

Return type:

int

Union(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Union of two layers.

For more details: OGR_L_Union()

The first geometry field is always used.

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

Update(self, method_layer, result_layer, options=None, callback=0, callback_data=None) OGRErr

Update this layer with features from the update layer.

For more details: OGR_L_Update()

Parameters:
  • method_layer (Layer) -- the method layer. Should not be None.

  • result_layer (Layer) -- the layer where the features resulting from the operation are inserted. Should not be None.

  • options (list[str], optional) -- List of options (empty list is allowed). For example ["PROMOTE_TO_MULTI=YES"].

  • callback (Callable, optional) -- a GDALProgressFunc() compatible callback function for reporting progress or None.

  • callback_data (any) -- Argument to be passed to 'callback'. May be None.

Returns:

An error code if there was an error or the execution was interrupted, osgeo.ogr.OGRERR_NONE otherwise.

Return type:

int

UpdateFeature(self, feature, nUpdatedFieldsCount, nUpdatedGeomFieldsCount, bUpdateStyleString) OGRErr
UpsertFeature(self, feature) OGRErr

Rewrite an existing feature or create a new feature within a layer.

For more details: OGR_L_UpsertFeature()

Parameters:

feature (Feature) -- The feature to write to disk.

Returns:

osgeo.ogr.OGRERR_NONE on success.

Return type:

int

WriteArrow(obj, requested_schema=None, createFieldsFromSchema=None, options=[])

Write the content of the passed object, which must implement the __arrow_c_stream__ or __arrow_c_array__ interface, into the layer.

Parameters:
  • obj (object) -- Object implementing the __arrow_c_stream__ or __arrow_c_array__ interface

  • requested_schema (object, optional) -- The schema to which the stream should be casted. Passed as a PyCapsule containing a C ArrowSchema representation of the requested schema, or as an object implementing the __arrow_c_schema__ interface. Defaults to None.

  • createFieldsFromSchema (bool or None, optional) -- Whether Layer.CreateFieldFromArrowSchema() should be called. If None is specified, it is called if no fields have been created yet. Defaults to None.

  • options (list[str]) -- Options to pass to OGRLayer::CreateFieldFromArrowSchema() and OGRLayer::WriteArrowBatch()

WriteArrowBatch(self, schema, array, options=None) OGRErr
WriteArrowSchemaAndArrowArrayCapsule(self, schemaCapsule, arrayCapsule, createFieldsFromSchema, options=None) OGRErr
WriteArrowStreamCapsule(self, capsule, createFieldsFromSchema, options=None) OGRErr
WritePyArrow(pa_batch, options=[])

Write the content of the passed PyArrow batch (either a pyarrow.Table, a pyarrow.RecordBatch or a pyarrow.StructArray) into the layer.

See also the WriteArrow() method to be independent of PyArrow

property schema

Feature

class osgeo.ogr.Feature(*args, **kwargs)

Python proxy of an OGRFeature.

Clone(self) Feature

Duplicate a Feature. See OGRFeature::Clone().

Return type:

Feature

Dereference()
Destroy()

Once called, self has effectively been destroyed. Do not access. For backwards compatibility only

DumpReadable(self)

Print this feature in a human readable form.

This dumps the attributes and geometry. It doesn't include definition information other than field types and names nor does it report the geometry spatial reference system.

See OGRFeature::DumpReadable().

Examples

>>> with gdal.OpenEx('poly.shp', gdal.OF_VECTOR) as ds:
...     lyr = ds.GetLayer(0)
...     feature = lyr.GetNextFeature()
...     feature.DumpReadable()
...
OGRFeature(poly):0
  AREA (Real) = 215229.266
  EAS_ID (Integer64) = 168
  PRFEDEA (String) = 35043411
  POLYGON ((479819.84375 4765180.5,479690.1875 4765259.5,479647.0 4765369.5,479730.375 4765400.5,480039.03125 4765539.5,480035.34375 4765558.5,480159.78125 4765610.5,480202.28125 4765482.0,480365.0 4765015.5,480389.6875 4764950.0,480133.96875 4764856.5,480080.28125 4764979.5,480082.96875 4765049.5,480088.8125 4765139.5,480059.90625 4765239.5,480019.71875 4765319.5,479980.21875 4765409.5,479909.875 4765370.0,479859.875 4765270.0,479819.84375 4765180.5)) # no-check
DumpReadableAsString(self, options=None) retStringAndCPLFree *

Return feature information in a human-readable form. Returns the text printed by Feature.DumpReadable().

Return type:

str

Equal(self, feature) bool

Test if two features are the same.

Two features are considered equal if they reference the same FeatureDefn, have the same field values, and the same geometry (as tested by Geometry.Equal()) as well as the same feature id.

See OGRFeature::Equal().

Parameters:

feature (Feature) -- feature to test this one against

Return type:

bool

ExportToJson(as_object=False, options=None)

Export a GeoJSON object which represents the Feature.

Parameters:
  • as_object (bool, default = False) -- determines whether the returned value should be a Python object instead of a string.

  • options (dict or str) -- Options to pass to Geometry.ExportToJson()

Return type:

str or dict

FillUnsetWithDefault(self, bNotNullableOnly=FALSE, options=None)

Fill unset fields with default values that might be defined.

See OGRFeature::FillUnsetWithDefault().

Parameters:
  • bNotNullableOnly (bool) -- if we should fill only unset fields with a not-null constraint.

  • options (dict) -- unused currently.

GetDefnRef(self) FeatureDefn

Fetch the FeatureDefn associated with this Feature.

See OGRFeature::GetDefnRef().

Return type:

FeatureDefn

GetFID(self) GIntBig

Get feature identifier. See OGRFeature::GetFID()

Returns:

feature id or NullFID if none has been assigned.

Return type:

int

GetField(fld_index)

Get the value of a field in its native type.

Alternatively, the [] operator may be used.

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Examples

>>> with gdal.OpenEx("poly.shp", gdal.OF_VECTOR) as ds:
...     lyr = ds.GetLayer(0)
...     feature = lyr.GetNextFeature()
...     # name-based access
...     feature.GetField("EAS_ID")
...     feature["EAS_ID"]
...     # index-based access
...     index = feature.GetFieldIndex("EAS_ID")
...     feature.GetField(index)
...     feature[index]
...
168
168
168
168
GetFieldAsBinary(self, id) OGRErr
GetFieldAsBinary(self, field_name) OGRErr

Fetch field value as binary.

This method only works for OFTBinary and OFTString fields.

See OGRFeature::GetFieldAsBinary().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Return type:

bytearray

GetFieldAsDateTime(self, id)
GetFieldAsDateTime(self, field_name) None

Fetch field value as date and time.

Currently this method only works for OFTDate, OFTTime and OFTDateTime fields.

See OGRFeature::GetFieldAsDateTime().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

list containing [ year, month, day, hour, minute, second, timezone flag ]

Return type:

list

Examples

>>> from datetime import datetime
>>> from zoneinfo import ZoneInfo
>>> defn = ogr.FeatureDefn()
>>> defn.AddFieldDefn(ogr.FieldDefn('unknown', ogr.OFTDateTime))
>>> defn.AddFieldDefn(ogr.FieldDefn('local', ogr.OFTDateTime))
>>> defn.AddFieldDefn(ogr.FieldDefn('utc', ogr.OFTDateTime))
>>> feature = ogr.Feature(defn)
>>> feature['unknown'] = datetime.now()
>>> feature['local'] = datetime.now(ZoneInfo('America/Toronto'))
>>> feature['utc'] = datetime.now(ZoneInfo('UTC'))
>>> feature.GetFieldAsDateTime('unknown')
[2024, 3, 15, 20, 34, 52.594173431396484, 0] # random
>>> feature.GetFieldAsDateTime('local')
[2024, 3, 15, 20, 34, 52.59502410888672, 84] # random
>>> feature.GetFieldAsDateTime('utc')
[2024, 3, 16, 0, 34, 52.59580993652344, 100] # random
GetFieldAsDouble(self, id) double
GetFieldAsDouble(self, field_name) double

Fetch field value as a double.

OFTString features will be translated using CPLAtof(). OFTInteger fields will be cast to double. Other field types, or errors will result in a return value of zero.

See OGRFeature::GetFieldAsDouble().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

float

GetFieldAsDoubleList(self, id)
GetFieldAsDoubleList(self, field_name) None

Fetch field value as a list of doubles.

Currently this function only works for OFTRealList fields.

See OGRFeature::GetFieldAsDoubleList().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Return type:

list

Examples

>>> defn = ogr.FeatureDefn()
>>> defn.AddFieldDefn(ogr.FieldDefn('list', ogr.OFTRealList))
>>> feature = ogr.Feature(defn)
>>> feature['list'] = [1.1, 2.2, 3.3]
>>> feature.GetFieldAsDoubleList('list')
[1.1, 2.2, 3.3]
GetFieldAsISO8601DateTime(self, id, options=None) char const
GetFieldAsISO8601DateTime(self, field_name, options=None) char const *

Fetch OFTDateTime field value as a ISO8601 representation.

Return a string like 'YYYY-MM-DDTHH:MM:SS(.sss)?(Z|([+|-]HH:MM))?' Milliseconds are omitted if equal to zero. Other field types, or errors will result in a return of an empty string.

See OGRFeature::GetFieldAsISO8601DateTime().

Added in version 3.7.

Parameters:
  • fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

  • options (dict or str) -- Not currently used.

GetFieldAsInteger(self, id) int
GetFieldAsInteger(self, field_name) int

Fetch field value as a 32-bit integer.

OFTString features will be translated using atoi(). OFTReal fields will be cast to integer. Other field types, or errors will result in a return value of zero.

See OGRFeature::GetFieldAsInteger().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

int

Examples

>>> defn = ogr.FeatureDefn()
>>> defn.AddFieldDefn(ogr.FieldDefn('my_int', ogr.OFTInteger64))
>>> feature = ogr.Feature(defn)
>>> feature['my_int'] = 2**32 + 1
>>> feature.GetFieldAsInteger('my_int')
Warning 1: Integer overflow occurred when trying to return 64bit integer. Use GetFieldAsInteger64() instead
2147483647
>>> feature.GetFieldAsInteger64('my_int')
4294967297
>>> feature.GetField('my_int')
4294967297
GetFieldAsInteger64(self, id) GIntBig
GetFieldAsInteger64(self, field_name) GIntBig

Fetch field value as integer 64 bit.

OFTInteger are promoted to 64 bit. OFTString features will be translated using CPLAtoGIntBig(). OFTReal fields will be cast to integer. Other field types, or errors will result in a return value of zero.

See OGRFeature::GetFieldAsInteger64().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

int

GetFieldAsInteger64List(self, id)

Fetch field value as a list of 64 bit integers.

Currently this function only works for OFTInteger64List fields.

See OGRFeature::GetFieldAsInteger64List().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

list

GetFieldAsIntegerList(self, id)
GetFieldAsIntegerList(self, field_name) None

Fetch field value as a list of integers.

Currently this function only works for OFTIntegerList fields.

This function is the same as the C++ method OGRFeature::GetFieldAsIntegerList().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

list

GetFieldAsString(self, id) char const
GetFieldAsString(self, field_name) char const *

OFTReal and OFTInteger fields will be translated to string using sprintf(), but not necessarily using the established formatting rules. Other field types, or errors will result in a return value of zero.

See OGRFeature::GetFieldAsString().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

str

GetFieldAsStringList(self, id) char **

Fetch field value as a list of strings.

Currently this method only works for OFTStringList fields.

See OGRFeature::GetFieldAsStringList().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

the field value.

Return type:

list

GetFieldCount(self) int

Fetch number of fields on this feature This will always be the same as the field count for the FeatureDefn.

See OGRFeature::GetFieldCount().

Returns:

count of fields.

Return type:

int

GetFieldDefnRef(self, id) FieldDefn
GetFieldDefnRef(self, field_name) FieldDefn

Fetch definition for this field.

See OGRFeature::GetFieldDefnRef().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

a reference to the field definition. This reference should not be modified.

Return type:

FieldDefn

GetFieldIndex(self, field_name) int

Fetch the field index given field name.

See OGRFeature::GetFieldIndex().

Parameters:

field_name (str) -- the name of the field to search for.

Returns:

the field index, or -1 if no matching field is found.

Return type:

int

GetFieldType(self, id) OGRFieldType
GetFieldType(self, field_name) OGRFieldType

Return the type of the given field.

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

field type code (e.g., OFTInteger)

Return type:

int

GetGeomFieldCount(self) int

Fetch number of geometry fields on this feature This will always be the same as the geometry field count for the FeatureDefn.

See OGRFeature::GetGeomFieldCount().

Returns:

count of geometry fields.

Return type:

int

GetGeomFieldDefnRef(self, id) GeomFieldDefn
GetGeomFieldDefnRef(self, field_name) GeomFieldDefn

Fetch definition for this geometry field.

See OGRFeature::GetGeomFieldDefnRef().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

a reference to the field definition. Should not be deleted or modified.

Return type:

GeomFieldDefn

GetGeomFieldIndex(self, field_name) int

Fetch the geometry field index given geometry field name.

See OGRFeature::GetGeomFieldIndex().

Parameters:

field_name (str) -- the name of the geometry field to search for.

Returns:

the geometry field index, or -1 if no matching geometry field is found.

Return type:

int

GetGeomFieldRef(self, iField) Geometry
GetGeomFieldRef(self, field_name) Geometry

Fetch a feature Geometry.

See OGRFeature::GetGeomFieldRef().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Return type:

Geometry

GetGeometryRef(self) Geometry

Return the feature geometry

The lifetime of the returned geometry is bound to the one of its belonging feature.

See OGRFeature::GetGeometryRef()

The Feature.geometry() method is also available as an alias of Feature.GetGeometryRef().

Returns:

the geometry, or None.

Return type:

Geometry

GetNativeData(self) char const *

Returns the native data for the feature.

The native data is the representation in a "natural" form that comes from the driver that created this feature, or that is aimed at an output driver. The native data may be in different format, which is indicated by GetNativeMediaType().

Note that most drivers do not support storing the native data in the feature object, and if they do, generally the NATIVE_DATA open option must be passed at dataset opening.

The "native data" does not imply it is something more performant or powerful than what can be obtained with the rest of the API, but it may be useful in round-tripping scenarios where some characteristics of the underlying format are not captured otherwise by the OGR abstraction.

See OGRFeature::GetNativeData() and RFC 60 : Improved round-tripping in OGR.

Returns:

a string with the native data, or None.

Return type:

str

GetNativeMediaType(self) char const *

Returns the native media type for the feature.

The native media type is the identifier for the format of the native data. It follows the IANA RFC 2045 (see https://en.wikipedia.org/wiki/Media_type), e.g. "application/vnd.geo+json" for JSon.

See OGRFeature::GetNativeMediaType() and RFC 60 : Improved round-tripping in OGR.

Returns:

a string with the native media type, or None.

Return type:

str

GetStyleString(self) char const *

Fetch style string for this feature.

Set the OGR Feature Style Specification for details on the format of this string, and ogr_featurestyle.h for services available to parse it.

See OGRFeature::GetStyleString().

Return type:

str or None

IsFieldNull(self, id) bool
IsFieldNull(self, field_name) bool

Test if a field is null.

See :cpp:func:OGRFeature::IsFieldNull.

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

True if the field is null, otherwise False

Return type:

bool

IsFieldSet(self, id) bool
IsFieldSet(self, field_name) bool

Test if a field has ever been assigned a value or not.

See OGRFeature::IsFieldSet().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

True if the field has been set, otherwise False.

Return type:

bool

IsFieldSetAndNotNull(self, id) bool
IsFieldSetAndNotNull(self, field_name) bool

Test if a field is set and not null.

See OGRFeature::IsFieldSetAndNotNull().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

True if the field is set and not null, otherwise False.

Return type:

bool

Reference()
SetFID(self, fid) OGRErr

Set the feature identifier.

For specific types of features this operation may fail on illegal features ids. Generally it always succeeds. Feature ids should be greater than or equal to zero, with the exception of :py:const:NullFID` (-1) indicating that the feature id is unknown.

See OGRFeature::SetFID().

Parameters:

fid (int) -- the new feature identifier value to assign.

Returns:

OGRERR_NONE on success, or some other value on failure.

Return type:

int

SetField(self, fld_index, value: str)
SetField(self, fld_name, value: str) None
SetField(self, fld_index, value: int) None
SetField(self, fld_name, value: int) None
SetField(self, fld_index, value: float) None
SetField(self, fld_name, value: float) None
SetField(self, fld_index, year: int, month: int, day: int, hour: int, minute: int, second: int | float, tzflag: int) None
SetField(self, fld_name, year: int, month: int, day: int, hour: int, minute: int, second: int | float, tzflag: int) None
SetField(self, fld_index, value: bytes) None
SetField(self, fld_name, value: bytes) None
SetFieldBinary(Feature self, field_index_or_name: int | str, value: bytes)

Set field to binary data. This function currently only has an effect on OFTBinary fields. This function is the same as the C++ method OGRFeature::SetField().

Parameters:
  • field_index_or_name (int or str) -- the field to set, from 0 to GetFieldCount()-1. Or the field name

  • values (any) -- the data to apply.

SetFieldBinaryFromHexString(self, id, pszValue)
SetFieldBinaryFromHexString(self, field_name, pszValue) None
SetFieldDoubleList(self, id, nList)

Set field to list of double values.

This function currently on has an effect of OFTIntegerList, OFTInteger64List, OFTRealList fields.

See OGRFeature::SetField().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:
  • id (int) -- the field to set, from 0 to GetFieldCount()-1.

  • nList (list) -- the values to assign.

SetFieldInteger64(self, id, value)
SetFieldInteger64List(self, id, nList)

void

Set field to list of 64 bit integer values.

This function currently on has an effect of OFTIntegerList, OFTInteger64List, OFTRealList fields.

See OGRFeature::SetField().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:
  • id (int) -- the field to set, from 0 to GetFieldCount()-1.

  • nList (list) -- the values to assign.

SetFieldIntegerList(self, id, nList)

void

Set field to list of integer values.

This function currently on has an effect of OFTIntegerList, OFTInteger64List, OFTRealList fields.

See OGRFeature::SetField().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:
  • id (int) -- the field to set, from 0 to GetFieldCount()-1.

  • nList (list) -- the values to assign.

SetFieldNull(self, id)
SetFieldNull(self, field_name) None

Clear a field, marking it as null.

See OGRFeature::SetFieldNull().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

SetFieldString(self, id, value)

Set field to string value.

OFTInteger fields will be set based on an atoi() conversion of the string. OFTInteger64 fields will be set based on an CPLAtoGIntBig() conversion of the string. OFTReal fields will be set based on an CPLAtof() conversion of the string. Other field types may be unaffected.

See OGRFeature::SetField().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:
  • fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

  • value (any) -- the value to assign.

SetFieldStringList(self, id, pList)

Set field to list of strings value.

This function currently only has an effect of OFTStringList fields.

See OGRFeature::SetField().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:
  • fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

  • value (any) -- the value to assign.

SetFrom(self, other, forgiving=1) OGRErr

Set one feature from another.

Overwrite the contents of this feature from the geometry and attributes of another. The other feature does not need to have the same FeatureDefn. Field values are copied by corresponding field names. Field types do not have to exactly match. OGR_F_SetField*() function conversion rules will be applied as needed.

See OGRFeature::SetFrom().

Parameters:
  • other (Feature) -- feature from which geometry and field values will be copied.

  • forgiving (bool, default = True) -- True if the operation should continue despite lacking output fields matching some of the source fields.

Returns:

OGRERR_NONE if the operation succeeds, even if some values are not transferred, otherwise an error code.

Return type:

int

SetFromWithMap(self, other, forgiving, nList) OGRErr

Set one feature from another.

Overwrite the contents of this feature from the geometry and attributes of another. The other feature does not need to have the same FeatureDefn. Field values are copied according to the provided indices map. Field types do not have to exactly match. OGR_F_SetField*() function conversion rules will be applied as needed. This is more efficient than :py:meth:SetFrom` in that this doesn't lookup the fields by their names. Particularly useful when the field names don't match.

See OGRFeature::SetFrom().

Parameters:
  • other (Feature) -- handle to the feature from which geometry, and field values will be copied.

  • forgiving (bool) -- True if the operation should continue despite lacking output fields matching some of the source fields.

  • nList (list) -- Array of the indices of the destination feature's fields stored at the corresponding index of the source feature's fields. A value of -1 should be used to ignore the source's field. The array should not be NULL and be as long as the number of fields in the source feature.

Returns:

OGRERR_NONE if the operation succeeds, even if some values are not transferred, otherwise an error code.

Return type:

int

SetGeomField(self, iField, geom) OGRErr
SetGeomField(self, field_name, geom) OGRErr

Set feature geometry of a specified geometry field.

This function updates the features geometry, and operates exactly as SetGeomFieldDirectly(), except that this function does not assume ownership of the passed geometry, but instead makes a copy of it.

See OGRFeature::SetGeomField().

Parameters:
  • fld_index (int or str) -- Geometry field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

  • geom (Geometry) -- handle to the new geometry to apply to feature.

Returns:

OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the FeatureDefn (checking not yet implemented).

Return type:

int

SetGeomFieldDirectly(field, geom)

Set feature geometry of a specified geometry field.

This function updates the features geometry, and operates exactly as SetGeomField(), except that this function assumes ownership of the passed geometry (even in case of failure of that function).

See OGRFeature::SetGeomFieldDirectly().

Parameters:
  • fld_index (int or str) -- Geometry field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

  • geom (Geometry) -- handle to the new geometry to apply to feature.

Returns:

OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the FeatureDefn (checking not yet implemented).

Return type:

int

SetGeometry(self, geom) OGRErr

Set feature geometry.

This function updates the features geometry, and operates exactly as SetGeometryDirectly(), except that this function does not assume ownership of the passed geometry, but instead makes a copy of it.

See OGRFeature::SetGeometry().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:

geom (Geometry) -- new geometry to apply to feature.

Returns:

OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the FeatureDefn (checking not yet implemented).

Return type:

int

SetGeometryDirectly(geom)

Set feature geometry.

This function updates the features geometry, and operates exactly as SetGeometry(), except that this function assumes ownership of the passed geometry (even in case of failure of that function).

See OGRFeature::SetGeometryDirectly().

This method has only an effect on the in-memory feature object. If this object comes from a layer and the modifications must be serialized back to the datasource, Layer.SetFeature() must be used afterwards. Or if this is a new feature, Layer.CreateFeature() must be used afterwards.

Parameters:

geom (Geometry) -- geometry to apply to feature.

Returns:

OGRERR_NONE if successful, or OGR_UNSUPPORTED_GEOMETRY_TYPE if the geometry type is illegal for the FeatureDefn (checking not yet implemented).

Return type:

int

SetNativeData(self, nativeData)

Sets the native data for the feature.

The native data is the representation in a "natural" form that comes from the driver that created this feature, or that is aimed at an output driver. The native data may be in different format, which is indicated by GetNativeMediaType().

See OGRFeature::SetNativeData() and RFC 60 : Improved round-tripping in OGR.

Parameters:

nativeData (str) -- a string with the native data, or None

SetNativeMediaType(self, nativeMediaType)

Sets the native media type for the feature.

The native media type is the identifier for the format of the native data. It follows the IANA RFC 2045 (see https://en.wikipedia.org/wiki/Media_type), e.g. "application/vnd.geo+json" for JSon.

See OGRFeature::SetNativeMediaType() and RFC 60 : Improved round-tripping in OGR.

Parameters:

nativeMediaType (str) -- a string with the native media type, or None

SetStyleString(self, the_string)

Set feature style string.

See OGRFeature::SetStyleString().

Parameters:

the_string (str) -- the style string to apply to this feature

UnsetField(self, id)
UnsetField(self, field_name) None

Clear a field, marking it as unset.

See OGRFeature::UnsetField().

Parameters:

fld_index (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Validate(self, flags=OGR_F_VAL_ALL, bEmitError=TRUE) int

Validate that a feature meets constraints of its schema.

The scope of test is specified with the flags parameter.

Regarding OGR_F_VAL_WIDTH, the test is done assuming the string width must be interpreted as the number of UTF-8 characters. Some drivers might interpret the width as the number of bytes instead. So this test is rather conservative (if it fails, then it will fail for all interpretations).

See OGRFeature::Validate().

Parameters:
  • flags (int, default = F_VAL_ALL) -- One or more of OGR_F_VAL_NULL, OGR_F_VAL_GEOM_TYPE, py:const:OGR_F_VAL_WIDTH and OGR_F_VAL_ALLOW_NULL_WHEN_DEFAULT combined with the with | operator

  • bEmitError (bool, default = True) -- TRUE if a CPLError() must be emitted when a check fails

Returns:

TRUE if all enabled validation tests pass.

Return type:

int

geometry()

Return the feature geometry

The lifetime of the returned geometry is bound to the one of its belonging feature.

For more details: OGR_F_GetGeometryRef()

The GetGeometryRef() method is also available as an alias of geometry()

Return type:

Geometry or None

items()

Return a dictionary with the field names as key, and their value in the feature

keys()

Return the list of field names (of the layer definition)

Geometry

class osgeo.ogr.Geometry(*args, **kwargs)

Proxy of C++ OGRGeometryShadow class.

AddGeometry(self, other) OGRErr
AddGeometryDirectly(self, other_disown) OGRErr
AddPoint(self, x, y, z=0) OGRErr

Add a point to a geometry (line string or point).

The vertex count of the line string is increased by one, and assigned from the passed location value.

The geometry is promoted to include a Z component, if it does not already have one, even if the Z parameter is not explicitly specified. To avoid that use AddPoint_2D.

This is the same as OGR_G_AddPoint()

Parameters:
  • X (float) -- x coordinate of point to add.

  • Y (float) -- y coordinate of point to add.

  • Z (float) -- z coordinate of point to add. Defaults to 0

Examples

>>> pt = ogr.Geometry(ogr.wkbPoint)
>>> ogr.GeometryTypeToName(pt.GetGeometryType())
'Point'
>>> pt.AddPoint(3, 7)
0
>>> ogr.GeometryTypeToName(pt.GetGeometryType())
'3D Point'
AddPointM(self, x, y, m) OGRErr
AddPointZM(self, x, y, z, m) OGRErr
AddPoint_2D(self, x, y) OGRErr

Add a point to a geometry (line string or point).

The vertex count of the line string is increased by one, and assigned from the passed location value.

If the geometry includes a Z or M component, the value for those components for the added point will be 0.

This is the same as OGR_G_AddPoint_2D()

Parameters:
  • X (float) -- x coordinate of point to add.

  • Y (float) -- y coordinate of point to add.

Examples

>>> pt = ogr.Geometry(ogr.wkbPoint)
>>> ogr.GeometryTypeToName(pt.GetGeometryType())
'Point'
>>> pt.AddPoint_2D(3, 7)
0
>>> ogr.GeometryTypeToName(pt.GetGeometryType())
'Point'
Area(self) double

Compute geometry area.

The returned area is a 2D Cartesian (planar) area in square units of the spatial reference system in use, so potentially 'square degrees' for a geometry expressed in a geographic SRS.

For more details: OGR_G_Area()

Returns:

the area of the geometry in square units of the spatial reference system in use, or 0.0 for unsupported geometry types.

Return type:

float

AssignSpatialReference(self, reference)

Assign spatial reference to this object.

For more details: OGR_G_AssignSpatialReference()

Parameters:

reference (SpatialReference) -- The new spatial reference system to apply.

Boundary(self) Geometry

Compute boundary.

For more details: OGR_G_Boundary()

Returns:

A new geometry or None on failure.

Return type:

Geometry

Buffer(self, distance, quadsecs=30) Geometry
Buffer(self, distance, options) Geometry

Compute buffer of geometry.

For more details: OGR_G_Buffer()

Parameters:
  • distance (float) -- The buffer distance to be applied. Should be expressed into the same unit as the coordinates of the geometry.

  • quadsecs (int, default=30) -- The number of segments used to approximate a 90 degree (quadrant) of curvature.

  • options (list or dict, optional) -- An optional list of options to control the buffer output. See OGR_G_BufferEx().

Returns:

The newly created geometry or None if an error occurs.

Return type:

Geometry

BuildArea(self) Geometry

Polygonize a linework assuming inner polygons are holes.

For more details: OGR_G_BuildArea()

Returns:

A new geometry or None on failure.

Return type:

Geometry

Centroid(self) Geometry

Compute the geometry centroid.

For more details: OGR_G_Centroid()

Return type:

Geometry

Clone(self) Geometry

Make a copy of this object.

For more details: OGR_G_Clone()

Returns:

The copy of the geometry with the same spatial reference system as the original.

Return type:

Geometry

CloseRings(self)

Force rings to be closed.

For more details: OGR_G_CloseRings()

ConcaveHull(self, ratio, allowHoles) Geometry

Compute the concave hull of a geometry.

For more details: OGR_G_ConcaveHull()

See also ConcaveHullOfPolygons()

Parameters:
  • ratio (float) -- Ratio of the area of the convex hull and the concave hull.

  • allowHoles (bool) -- Whether the concave hull is allowed to contain holes.

Returns:

The concave hull geometry or None if an error occurs.

Return type:

Geometry

ConcaveHullOfPolygons(self, lengthRatio, isTight, allowHoles) Geometry

Compute the concave hull of a set of polygons, respecting the polygons as constraints.

For more details: OGR_G_ConcaveHullOfPolygons()

Parameters:
  • lengthRatio (float) -- Specifies the Maximum Edge Length as a fraction of the difference between the longest and shortest edge lengths between the polygons. This normalizes the Maximum Edge Length to be scale-free. A value of 1 produces the convex hull; a value of 0 produces the original polygons.

  • isTight (bool) -- Whether the hull must follow the outer boundaries of the input polygons.

  • allowHoles (bool) -- Whether the concave hull is allowed to contain holes.

Returns:

The concave hull geometry or None if an error occurs.

Return type:

Geometry

ConstrainedDelaunayTriangulation(self) Geometry

Return a constrained Delaunay triangulation of the vertices of the given polygon(s). For non-polygonal inputs, silently returns an empty geometry collection.

For more details: OGR_G_ConstrainedDelaunayTriangulation()

Added in version 3.12.

Returns:

The geometry collection resulting from the constrained Delaunay triangulation or None if an error occurs.

Return type:

Geometry

Contains(self, other) bool

Test for containment.

For more details: OGR_G_Contains()

Parameters:

other (Geometry) -- the other geometry to compare.

Returns:

True if this contains the other geometry, otherwise False.

Return type:

int

ConvexHull(self) Geometry

Compute convex hull.

For more details: OGR_G_ConvexHull()

Returns:

a handle to A newly allocated geometry now owned by the caller, or None on failure.

Return type:

Geometry

CoordinateDimension(self) int

Get the dimension of the coordinates in this geometry.

For more details: OGR_G_CoordinateDimension()

Added in version 2.1.

Returns:

This will return 2 for XY, 3 for XYZ and XYM, and 4 for XYZM data.

Return type:

int

CreatePreparedGeometry(self) PreparedGeometry
Crosses(self, other) bool

Test for crossing.

For more details: OGR_G_Crosses()

Parameters:

other (Geometry) -- the other geometry to compare.

Returns:

True if they are crossing, otherwise False.

Return type:

int

DelaunayTriangulation(self, dfTolerance=0.0, bOnlyEdges=FALSE) Geometry

Return a Delaunay triangulation of the vertices of the geometry.

For more details: OGR_G_DelaunayTriangulation()

Added in version 2.1.

Parameters:
  • dfTolerance (float) -- optional snapping tolerance to use for improved robustness

  • bOnlyEdges (bool) -- If True, will return a MULTILINESTRING, otherwise it will return a GEOMETRYCOLLECTION containing triangular POLYGONs.

Returns:

The geometry resulting from the Delaunay triangulation or None if an error occurs.

Return type:

Geometry

Destroy()
Difference(self, other) Geometry

Compute difference.

For more details: OGR_G_Difference()

Parameters:

other (Geometry) -- The other geometry.

Returns:

A new geometry representing the difference or None if the difference is empty or an error occurs.

Return type:

Geometry

Disjoint(self, other) bool

Test for disjointness.

For more details: OGR_G_Disjoint()

Parameters:

other (Geometry) -- The other geometry to compare.

Returns:

True if they are disjoint, otherwise False.

Return type:

int

Distance(self, other) double

Compute distance between two geometries.

For more details: OGR_G_Distance()

Parameters:

other (Geometry) -- The other geometry to compare against.

Returns:

The distance between the geometries or -1 if an error occurs.

Return type:

float

Distance3D(self, other) double

Returns the 3D distance between two geometries.

For more details: OGR_G_Distance3D()

Added in version 2.2.

Parameters:

other (Geometry) -- The other geometry to compare against.

Returns:

The distance between the geometries or -1 if an error occurs.

Return type:

float

Empty(self)

Clear geometry information.

For more details: OGR_G_Empty()

Equal(self, other) bool
Equals(self, other) bool

Returns True if two geometries are equivalent.

For more details: OGR_G_Equals()

Parameters:

other (Geometry) -- The other geometry to test against.

Returns:

True if equivalent or False otherwise.

Return type:

int

ExportToGML(self, options=None) retStringAndCPLFree *
ExportToIsoWkb(self, byte_order=wkbNDR) OGRErr

Convert a geometry into SFSQL 1.2 / ISO SQL/MM Part 3 well known binary format.

For more details: OGR_G_ExportToIsoWkb()

Added in version 2.0.

Parameters:

byte_order (int, optional) -- One of osgeo.ogr.wkbXDR or osgeo.ogr.wkbNDR, indicating MSB (most significant byte) or LSB (least significant byte) byte order. Defaults to osgeo.ogr.wkbNDR.

Return type:

bytes

ExportToIsoWkt(self) OGRErr

Convert a geometry into SFSQL 1.2 / ISO SQL/MM Part 3 well known text format.

For more details: OGR_G_ExportToIsoWkt()

Added in version 2.0.

Return type:

str

ExportToJson(self, options=None) retStringAndCPLFree *
ExportToKML(self, altitude_mode=None) retStringAndCPLFree *
ExportToWkb(self, byte_order=wkbNDR) OGRErr

Convert a geometry well known binary format.

For more details: OGR_G_ExportToWkb()

Parameters:

byte_order (int, optional) -- One of osgeo.ogr.wkbXDR or osgeo.ogr.wkbNDR, indicating MSB (most significant byte) or LSB (least significant byte) byte order. Defaults to osgeo.ogr.wkbNDR.

Return type:

bytes

ExportToWkt(self) OGRErr

Convert a geometry into well known text format.

For more details: OGR_G_ExportToWkt()

Return type:

str

FlattenTo2D(self)

Convert geometry to strictly 2D.

For more details: OGR_G_FlattenTo2D()

GeodesicArea(self) double

Compute geometry area, considered as a surface on the underlying ellipsoid of the SRS attached to the geometry.

For more details: OGR_G_GeodesicArea()

Returns:

the area in square meters, or a negative value for unsupported geometry types.

Return type:

float

GeodesicLength(self) double

Compute geometry length, considered as a curve on the underlying ellipsoid of the SRS attached to the geometry.

For more details: OGR_G_GeodesicLength()

Returns:

the area in meters, or a negative value for unsupported geometry types.

Return type:

float

GetArea(self) double
GetBoundary(self) Geometry

Compute boundary (deprecated)

For more details: OGR_G_GetBoundary()

..warning:: Deprecated

See: OGR_G_Boundary()

GetCoordinateDimension(self) int

Get the dimension of the coordinates in this geometry.

For more details: OGR_G_GetCoordinateDimension()

Warning

Deprecated. Use CoordinateDimension(), Is3D(), or IsMeasured().

Returns:

This will return 2 or 3.

Return type:

int

GetCurveGeometry(self, options=None) Geometry
GetDimension(self) int

Get the dimension of this geometry.

For more details: OGR_G_GetDimension()

Returns:

0 for points, 1 for lines, and 2 for surfaces.

Return type:

int

GetEnvelope(self)

Computes and returns the bounding envelope for this geometry in the passed psEnvelope structure.

For more details: OGR_G_GetEnvelope()

Warning

Check the return order of the bounds.

Returns:

(minx, maxx, miny, maxy)

Return type:

tuple of float

GetEnvelope3D(self)

Computes and returns the bounding envelope (3D) for this geometry in the passed psEnvelope structure.

For more details: OGR_G_GetEnvelope3D()

Warning

Check the return order of the bounds.

Returns:

(minx, maxx, miny, maxy, minz, maxz)

Return type:

tuple of float

GetGeometryCount(self) int
GetGeometryName(self) char const *

Fetch WKT name for geometry type.

For more details: OGR_G_GetGeometryName()

geometry to get name from.

Return type:

str

GetGeometryRef(self, geom) Geometry
GetGeometryType(self) OGRwkbGeometryType

Fetch geometry type.

For more details: OGR_G_GetGeometryType()

Returns:

The geometry type code. The types can be found with 'osgeo.ogr.wkb' prefix. For example osgeo.ogr.wkbPolygon.

Return type:

int

GetInvalidityReason(self) retStringAndCPLFree *

Test if the geometry is valid and, if not, return the invalidity reason.

For more details: OGR_G_GetInvalidityReason()

Returns:

a string with the invalidity reason, or None if it is valid

Return type:

str

GetLinearGeometry(self, dfMaxAngleStepSizeDegrees=0.0, options=None) Geometry
GetM(self, point=0) double
GetPoint(self, iPoint=0)
GetPointCount(self) int
GetPointZM(self, iPoint=0)
GetPoint_2D(self, iPoint=0)
GetPoints(self, nCoordDimension=0)
GetSpatialReference(self) SpatialReference

For more details: OGR_G_GetSpatialReference()

Returns spatial reference system for geometry.

Return type:

SpatialReference

GetX(self, point=0) double
GetY(self, point=0) double
GetZ(self, point=0) double
HasCurveGeometry(self, bLookForCircular=FALSE) int
Intersect(self, other) bool
Intersection(self, other) Geometry

Compute intersection.

For more details: OGR_G_Intersection()

Parameters:

other (Geometry) -- The other geometry.

Returns:

A new geometry representing the intersection or None if there is no intersection or an error occurs.

Return type:

Geometry

Intersects(self, other) bool

Determines whether two geometries intersect.

For more details: OGR_G_Intersects()

Parameters:

other (Geometry) -- The other geometry to test against.

Returns:

True if the geometries intersect, otherwise False.

Return type:

int

Is3D(self) int

See whether this geometry has Z coordinates.

For more details: OGR_G_Is3D()

Added in version 2.1.

Returns:

True if the geometry has Z coordinates.

Return type:

int

IsClockwise(self) bool
IsEmpty(self) bool

Test if the geometry is empty.

For more details: OGR_G_IsEmpty()

Returns:

True if the geometry has no points, otherwise False.

Return type:

int

IsMeasured(self) int

See whether this geometry is measured.

For more details: OGR_G_IsMeasured()

Added in version 2.1.

Returns:

True if the geometry has M coordinates.

Return type:

int

IsRing(self) bool

Test if the geometry is a ring.

For more details: OGR_G_IsRing()

Returns:

True if the coordinates of the geometry form a ring, by checking length and closure (self-intersection is not checked), otherwise False.

Return type:

int

IsSimple(self) bool

Returns True if the geometry is simple.

For more details: OGR_G_IsSimple()

Returns:

True if object is simple, otherwise False.

Return type:

int

IsValid(self) bool

Test if the geometry is valid.

For more details: OGR_G_IsValid()

Returns:

True if the geometry is invalid, otherwise False.

Return type:

int

Length(self) double

Compute geometry length.

The returned length is a 2D Cartesian (planar) area in units of the spatial reference system in use, so potentially 'degrees' for a geometry expressed in a geographic SRS.

For more details: OGR_G_Length()

Returns:

the length of the geometry in units of the spatial reference system in use, or 0.0 for unsupported geometry types.

Return type:

float

MakeValid(self, options=None) Geometry

Attempts to make an invalid geometry valid without losing vertices.

For more details: OGR_G_MakeValidEx()

Added in version 3.0.

Added in version 3.4: options

Parameters:

options (list[str], optional) -- papszOptions to be passed in. For example: ["METHOD=STRUCTURE"].

Returns:

A newly allocated geometry now owned by the caller, or None on failure.

Return type:

Geometry

Normalize(self) Geometry

Attempts to bring geometry into normalized/canonical form.

For more details: OGR_G_Normalize()

Added in version 3.3.

Returns:

A newly allocated geometry now owned by the caller, or None on failure.

Return type:

Geometry

Overlaps(self, other) bool

Test for overlap.

For more details: OGR_G_Overlaps()

Parameters:

other (Geometry) -- the other geometry to compare.

Returns:

True if they are overlapping, otherwise False.

Return type:

int

PointOnSurface(self) Geometry

Returns a point guaranteed to lie on the surface.

For more details: OGR_G_PointOnSurface()

Returns:

A point guaranteed to lie on the surface or None if an error occurred.

Return type:

Geometry

Polygonize(self) Geometry

Polygonizes a set of sparse edges.

For more details: OGR_G_Polygonize()

Returns:

A new geometry or None on failure.

Return type:

Geometry

RemoveGeometry(self, iSubGeom) OGRErr
RemoveLowerDimensionSubGeoms(self) Geometry
Segmentize(self, dfMaxLength)

Modify the geometry such it has no segment longer then the given distance.

For more details: OGR_G_Segmentize()

Parameters:

dfMaxLength (float) -- the maximum distance between 2 points after segmentization

Set3D(self, b3D)

Add or remove the Z coordinate dimension.

For more details: OGR_G_Set3D()

Added in version 2.1.

Parameters:

bIs3D (bool) -- Should the geometry have a Z dimension, either True or False.

SetCoordinateDimension(self, dimension)

Set the coordinate dimension.

For more details: OGR_G_SetCoordinateDimension()

Warning

Deprecated. Use Set3D() or SetMeasured().

Parameters:

dimension (int) -- New coordinate dimension value, either 2 or 3.

SetMeasured(self, bMeasured)

Add or remove the M coordinate dimension.

For more details: OGR_G_SetMeasured()

Added in version 2.1.

Parameters:

bIsMeasured (bool) -- Should the geometry have a M dimension, either True or False.

SetPoint(self, point, x, y, z=0) OGRErr
SetPointM(self, point, x, y, m) OGRErr
SetPointZM(self, point, x, y, z, m) OGRErr
SetPoint_2D(self, point, x, y) OGRErr
SetPrecision(self, gridSize, flags=0) Geometry
Simplify(self, tolerance) Geometry

Compute a simplified geometry.

For more details: OGR_G_Simplify()

Parameters:

tolerance (float) -- The distance tolerance for the simplification.

Returns:

The simplified geometry or None if an error occurs.

Return type:

Geometry

SimplifyPreserveTopology(self, tolerance) Geometry

Simplify the geometry while preserving topology.

For more details: OGR_G_SimplifyPreserveTopology()

Parameters:

tolerance (float) -- The distance tolerance for the simplification.

Returns:

The simplified geometry or None if an error occurs.

Return type:

Geometry

SwapXY(self)

Swap x and y coordinates.

For more details: OGR_G_SwapXY()

Added in version 2.3.0.

SymDifference(self, other) Geometry

Compute symmetric difference.

For more details: OGR_G_SymDifference()

Parameters:

other (Geometry) -- the other geometry.

Returns:

A new geometry representing the symmetric difference or None if the difference is empty or an error occurs.

Return type:

Geometry

SymmetricDifference(self, other) Geometry

Compute symmetric difference (deprecated)

For more details: OGR_G_SymmetricDifference()

Warning

Deprecated

Touches(self, other) bool

Test for touching.

For more details: OGR_G_Touches()

Parameters:

other (Geometry) -- the other geometry to compare.

Returns:

True if they are touching, otherwise False.

Return type:

int

Transform(self, trans) OGRErr
Transform(self, transformer) Geometry

Apply a coordinate transformation to the geometry.

The behavior of the function depends on the type of the provided argument.

If a osr.CoordinateTransformation is provided, the geometry will be transformed in-place, or an error code returned.

If a GeomTransformer is provided, the geometry will remain unmodified, and a transformed geometry will be returned.

See OGR_G_Transform() and OGR_GeomTransformer_Transform().

Parameters:

trans (CoordinateTransformation or GeomTransformer) -- The transformation to apply.

Returns:

The transformed geometry if trans is a GeomTransformer, or an error code if trans is a osr.CoordinateTransformation.

Return type:

Geometry or int

Examples

>>> # use a CoordinateTransformation to transform a geometry in-place
>>> wgs84 = osr.SpatialReference(epsg=4326)
>>> wgs84.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
>>> albers = osr.SpatialReference(epsg=9473)
>>> xform = osr.CoordinateTransformation(wgs84, albers)
>>> vt = ogr.Geometry(ogr.wkbPoint)
>>> vt.AddPoint_2D(145.195, -37.836)
0
>>> vt.Transform(xform)
0
>>> vt.GetPoint_2D()
(1166651.434325419, -4196676.777645577)
>>> # use a GeomTransformer and return a transformed geometry
>>> polar_stereo = osr.SpatialReference(epsg=3413)
>>> rect = ogr.CreateGeometryFromWkt('POLYGON((-3106890 145265,-3106890 2474514,-672244 2474514,-672244 145265,-3106890 145265))')
>>> xform = osr.CoordinateTransformation(polar_stereo, wgs84)
>>> xformer = ogr.GeomTransformer(xform, {'WRAPDATELINE=TRUE':True, 'DATELINEOFFSET': 180})
>>> rect_transformed = rect.Transform(xformer)
>>> rect_transformed.ExportToWkt()
'MULTIPOLYGON (((150.198564480925 66.6449112280509,180.0 74.7428375082776,180.0 56.6419000989319,150.198564480925 66.6449112280509)),((-173.535923883218 54.4721983980102,-180 56.6419000989319,-180 74.7428375082776,-147.193543096797 83.6573164550226,-137.676958092793 61.8457340532701,-173.535923883218 54.4721983980102)))' # no-check
TransformTo(self, reference) OGRErr

Transform geometry to new spatial reference system.

For more details: OGR_G_TransformTo()

Parameters:

reference (SpatialReference) -- The spatial reference system to apply.

Returns:

osgeo.ogr.OGRERR_NONE on success, or an error code.

Return type:

int

UnaryUnion(self) Geometry
Union(self, other) Geometry

Compute union.

For more details: OGR_G_Union()

Parameters:

other (Geometry) -- The other geometry.

Returns:

A new geometry representing the union or None if an error occurs.

Return type:

Geometry

UnionCascaded(self) Geometry

Compute union using cascading.

For more details: OGR_G_UnionCascaded()

Returns:

A new geometry representing the union or None if an error occurs.

Return type:

Geometry

Value(self, dfDistance) Geometry
Within(self, other) bool

Test for containment.

For more details: OGR_G_Within()

Parameters:

other (Geometry) -- the other geometry to compare.

Returns:

True if this is within other, otherwise False.

Return type:

int

WkbSize(self) size_t

Returns size of related binary representation.

For more details: OGR_G_WkbSize()

Return type:

int

osgeo.ogr.CreateGeometryFromEsriJson(input_string) Geometry
osgeo.ogr.CreateGeometryFromGML(input_string) Geometry
osgeo.ogr.CreateGeometryFromJson(input_string) Geometry
osgeo.ogr.CreateGeometryFromWkb(len, reference=None) Geometry
osgeo.ogr.CreateGeometryFromWkt(val, reference=None) Geometry
osgeo.ogr.ForceTo(geom_in, eTargetType, options=None) Geometry
osgeo.ogr.ForceToLineString(geom_in) Geometry
osgeo.ogr.ForceToMultiLineString(geom_in) Geometry
osgeo.ogr.ForceToMultiPoint(geom_in) Geometry
osgeo.ogr.ForceToMultiPolygon(geom_in) Geometry
osgeo.ogr.ForceToPolygon(geom_in) Geometry
osgeo.ogr.GeometryTypeToName(eType) char const *
osgeo.ogr.GT_Flatten(eType) OGRwkbGeometryType
osgeo.ogr.GT_GetCollection(eType) OGRwkbGeometryType
osgeo.ogr.GT_GetCurve(eType) OGRwkbGeometryType
osgeo.ogr.GT_GetLinear(eType) OGRwkbGeometryType
osgeo.ogr.GT_HasM(eType) int
osgeo.ogr.GT_HasZ(eType) int
osgeo.ogr.GT_IsCurve(arg1) int
osgeo.ogr.GT_IsNonLinear(arg1) int
osgeo.ogr.GT_IsSubClassOf(eType, eSuperType) int
osgeo.ogr.GT_IsSurface(arg1) int
osgeo.ogr.GT_SetM(eType) OGRwkbGeometryType
osgeo.ogr.GT_SetModifier(eType, bSetZ, bSetM=FALSE) OGRwkbGeometryType
osgeo.ogr.GT_SetZ(eType) OGRwkbGeometryType

FeatureDefn

class osgeo.ogr.FeatureDefn(*args, **kwargs)

Python proxy of an OGRFeatureDefn.

AddFieldDefn(self, defn)

Add a new field definition.

To add a new field definition to a layer definition, do not use this function directly, but use Layer.CreateField() instead.

This function should only be called while there are no Feature objects in existence based on this FeatureDefn. The FieldDefn passed in is copied.

See OGRFeatureDefn::AddFieldDefn().

Parameters:

defn (FieldDefn) -- the new field definition.

AddGeomFieldDefn(self, defn)

Add a new geometry field definition.

To add a new field definition to a layer definition, do not use this function directly, but use Layer.CreateGeomField() instead.

This function should only be called while there are no Feature objects in existence based on this FeatureDefn. The GeomFieldDefn passed in is copied.

See OGRFeatureDefn::AddGeomFieldDefn().

Parameters:

defn (GeomFieldDefn) -- new geometry field definition.

DeleteGeomFieldDefn(self, idx) OGRErr

Delete an existing geometry field definition.

To delete an existing geometry field definition from a layer definition, do not use this function directly, but use Layer.DeleteGeomField() instead ( not implemented yet).

This function should only be called while there are no Feature objects in existence based on this FeatureDefn.

See OGRFeatureDefn::DeleteGeomFieldDefn().

Parameters:

idx (int) -- the index of the geometry field definition.

Returns:

OGRERR_NONE in case of success.

Return type:

int

Destroy()

Once called, self has effectively been destroyed. Do not access. For backwards compatibility only

GetFieldCount(self) int

Fetch number of fields on the passed feature definition.

See OGRFeatureDefn::GetFieldCount().

Returns:

count of fields.

Return type:

int

GetFieldDefn(self, i) FieldDefn

Fetch field definition of the passed feature definition.

See OGRFeatureDefn::GetFieldDefn().

Parameters:

i (int or str) -- Field name or 0-based numeric index. For repeated access, use of the numeric index avoids a lookup step.

Returns:

internal field definition object or None if the field does not exist. This object should not be modified by the application.

Return type:

FieldDefn

GetFieldIndex(self, field_name) int

Find field by name.

The field index of the first field matching the passed field name (case insensitively) is returned.

See OGRFeatureDefn::GetFieldIndex().

Parameters:

field_name (str) -- the field name to search for.

Returns:

the field index, or -1 if no match found.

Return type:

int

GetGeomFieldCount(self) int

Fetch number of geometry fields on the passed feature definition.

See OGRFeatureDefn::GetGeomFieldCount().

Returns:

count of geometry fields.

Return type:

int

GetGeomFieldDefn(self, i) GeomFieldDefn

Fetch geometry field definition of the passed feature definition.

See OGRFeatureDefn::GetGeomFieldDefn().

Parameters:

i (int) -- the geometry field to fetch, between 0 and GetGeomFieldCount() - 1.

Returns:

an internal field definition object or None if invalid index. This object should not be modified by the application.

Return type:

GeomFieldDefn

GetGeomFieldIndex(self, field_name) int

Find geometry field by name.

The geometry field index of the first geometry field matching the passed field name (case insensitively) is returned.

See OGRFeatureDefn::GetGeomFieldIndex().

Parameters:

field_name (str) -- the geometry field name to search for.

Returns:

the geometry field index, or -1 if no match found.

Return type:

int

GetGeomType(self) OGRwkbGeometryType

Fetch the geometry base type of the passed feature definition.

This is equivalent to GetGeomFieldDefn(0).GetType().

See OGRFeatureDefn::GetGeomType().

Returns:

the base type for all geometry related to this definition.

Return type:

int

GetName(self) char const *

Get name of the FeatureDefn.

See OGRFeatureDefn::GetName().

Returns:

the name

Return type:

str

GetReferenceCount(self) int

Fetch current reference count.

See OGRFeatureDefn::GetReferenceCount().

Returns:

the current reference count.

Return type:

int

IsGeometryIgnored(self) int

Determine whether the geometry can be omitted when fetching features.

Equivalent to GetGeomFieldDefn(0).IsIgnored().

See OGRFeatureDefn::IsGeometryIgnored().

Returns:

ignore state

Return type:

int

IsSame(self, other_defn) int

Test if the feature definition is identical to the other one.

Parameters:

other_defn (FeatureDefn) -- other feature definition to compare to.

Returns:

1 if the feature definition is identical to the other one.

Return type:

int

IsStyleIgnored(self) int

Determine whether the style can be omitted when fetching features.

See OGRFeatureDefn::IsStyleIgnored().

Returns:

ignore state

Return type:

int

SetGeomType(self, geom_type)

Assign the base geometry type for the passed layer (the same as the feature definition).

This is equivalent to GetGeomFieldDefn(0).SetType().

All geometry objects using this type must be of the defined type or a derived type. The default upon creation is wkbUnknown which allows for any geometry type. The geometry type should generally not be changed after any Feature objects have been created against this definition.

See OGRFeatureDefn::SetGeomType().

Parameters:

geom_type (int) -- the new type to assign.

SetGeometryIgnored(self, bIgnored)

Set whether the geometry can be omitted when fetching features.

This is equivalent to GetGeomFieldDefn(0).SetIgnored().

See OGRFeatureDefn::SetGeometryIgnored().

Parameters:

bignored (bool) -- ignore state

SetStyleIgnored(self, bIgnored)

Set whether the style can be omitted when fetching features.

See OGRFeatureDefn::SetStyleIgnored().

Parameters:

bignored (bool) -- ignore state

FieldDefn

class osgeo.ogr.FieldDefn(*args, **kwargs)

Python proxy of an OGRFieldDefn.

Destroy()

Once called, self has effectively been destroyed. Do not access. For backwards compatibility only

GetAlternativeName(self) char const *
GetAlternativeNameRef(self) char const *

Fetch the alternative name (or "alias") for this field.

The alternative name is an optional attribute for a field which can provide a more user-friendly, descriptive name of a field which is not subject to the usual naming constraints defined by the data provider.

This is a metadata style attribute only: the alternative name cannot be used in place of the actual field name during SQL queries or other field name dependent API calls.

See OGRFieldDefn::GetAlternativeNameRef().

Added in version 3.2.

Returns:

the alternative name of the field definition.

Return type:

str

GetComment(self) char const *
GetDefault(self) char const *

Get default field value.

See OGRFieldDefn::GetDefault().

Returns:

default field value or None.

Return type:

str

GetDomainName(self) char const *

Return the name of the field domain for this field.

By default an empty string is returned.

Field domains ( FieldDomain class) are attached at the Dataset level and should be retrieved with Dataset.GetFieldDomain().

See OGRFieldDefn::GetDomainName().

Added in version 3.3.

Returns:

the field domain name, or an empty string if there is none.

Return type:

str

GetFieldTypeName(self, type) char const *
GetJustify(self) OGRJustification

Get the justification for this field.

See OGRFieldDefn::GetJustify().

Note: no driver is know to use the concept of field justification.

Returns:

the justification.

Return type:

int

GetName(self) char const *
GetNameRef(self) char const *

Fetch name of this field.

See OGRFieldDefn::GetNameRef().

Returns:

the name of the field definition.

Return type:

str

GetPrecision(self) int

Get the formatting precision for this field.

This should normally be zero for fields of types other than OFTReal.

See OGRFieldDefn::GetPrecision().

Returns:

the precision.

Return type:

int

GetSubType(self) OGRFieldSubType

Fetch subtype of this field.

See OGRFieldDefn::GetSubType().

Returns:

field subtype code, default = OFSTNone

Return type:

int

GetTZFlag(self) int
GetType(self) OGRFieldType

Fetch type of this field.

See OGRFieldDefn::GetType().

Returns:

field type code, e.g. OFTInteger

Return type:

int

GetTypeName(self) char const *
GetWidth(self) int

Get the formatting width for this field.

See OGRFieldDefn::GetWidth().

Returns:

the width, zero means no specified width.

Return type:

int

IsDefaultDriverSpecific(self) int

Returns whether the default value is driver specific.

Driver specific default values are those that are not NULL, a numeric value, a literal value enclosed between single quote characters, CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE or datetime literal value.

See OGRFieldDefn::IsDefaultDriverSpecific().

Returns:

TRUE if the default value is driver specific.

Return type:

int

IsGenerated(self) int
IsIgnored(self) int

Return whether this field should be omitted when fetching features.

See OGRFieldDefn::IsIgnored().

Returns:

ignore state

Return type:

int

IsNullable(self) int

Return whether this field can receive null values.

By default, fields are nullable.

Even if this method returns FALSE (i.e not-nullable field), it doesn't mean that Feature.IsFieldSet() will necessary return TRUE, as fields can be temporary unset and null/not-null validation is usually done when Layer.CreateFeature()/Layer.SetFeature() is called.

See OGRFieldDefn::IsNullable().

Returns:

TRUE if the field is authorized to be null.

Return type:

int

IsUnique(self) int

Return whether this field has a unique constraint.

By default, fields have no unique constraint.

See OGRFieldDefn::IsUnique().

Added in version 3.2.

Returns:

TRUE if the field has a unique constraint.

Return type:

int

SetAlternativeName(self, alternativeName)

Reset the alternative name (or "alias") for this field.

The alternative name is an optional attribute for a field which can provide a more user-friendly, descriptive name of a field which is not subject to the usual naming constraints defined by the data provider.

This is a metadata style attribute only: the alternative name cannot be used in place of the actual field name during SQL queries or other field name dependent API calls.

See OGRFieldDefn::SetAlternativeName().

Added in version 3.2.

Parameters:

alternativeName (str) -- the new alternative name to apply.

SetComment(self, comment)
SetDefault(self, pszValue)

Set default field value.

The default field value is taken into account by drivers (generally those with a SQL interface) that support it at field creation time. OGR will generally not automatically set the default field value to null fields by itself when calling OGRFeature::CreateFeature() / OGRFeature::SetFeature(), but will let the low-level layers to do the job. So retrieving the feature from the layer is recommended.

The accepted values are NULL, a numeric value, a literal value enclosed between single quote characters (and inner single quote characters escaped by repetition of the single quote character), CURRENT_TIMESTAMP, CURRENT_TIME, CURRENT_DATE or a driver specific expression (that might be ignored by other drivers). For a datetime literal value, format should be 'YYYY/MM/DD HH:MM:SS[.sss]' (considered as UTC time).

Drivers that support writing DEFAULT clauses will advertise the GDAL_DCAP_DEFAULT_FIELDS driver metadata item.

See OGRFieldDefn::SetDefault().

Parameters:

pszValue (str) -- new default field value or NULL pointer.

SetDomainName(self, name)

Set the name of the field domain for this field.

Field domains ( FieldDomain) are attached at the Dataset level.

See OGRFieldDefn::SetDomainName().

Added in version 3.3.

Parameters:

name (str) -- Field domain name.

SetGenerated(self, bGenerated)
SetIgnored(self, bIgnored)

Set whether this field should be omitted when fetching features.

See OGRFieldDefn::SetIgnored().

Parameters:

bignored (bool) -- ignore state

SetJustify(self, justify)

Set the justification for this field.

Note: no driver is know to use the concept of field justification.

See OGRFieldDefn::SetJustify().

Parameters:

justify (int) -- the new justification

Examples

>>> f = ogr.FieldDefn('desc', ogr.OFTString)
>>> f.SetJustify(ogr.OJRight)
SetName(self, name)

Reset the name of this field.

See OGRFieldDefn::SetName().

Parameters:

name (str) -- the new name to apply

SetNullable(self, bNullable)

Set whether this field can receive null values.

By default, fields are nullable, so this method is generally called with False to set a not-null constraint.

Drivers that support writing not-null constraint will advertise the GDAL_DCAP_NOTNULL_FIELDS driver metadata item.

See OGRFieldDefn::SetNullable().

Parameters:

bNullable (bool) -- False if the field must have a not-null constraint.

SetPrecision(self, precision)

Set the formatting precision for this field in characters.

This should normally be zero for fields of types other than OFTReal.

See OGRFieldDefn::SetPrecision().

Parameters:

precision (int) -- the new precision.

SetSubType(self, type)

Set the subtype of this field.

This should never be done to a FieldDefn that is already part of an :py:class:FeatureDefn`.

See OGRFieldDefn::SetSubType().

Parameters:

type -- the new field subtype.

Examples

>>> f = ogr.FieldDefn()
>>> f.SetType(ogr.OFTReal)
>>> f.SetSubType(ogr.OFSTJSON)
Warning 1: Type and subtype of field definition are not compatible. Resetting to OFSTNone
>>> f.SetSubType(ogr.OFSTFloat32)
SetTZFlag(self, tzflag)
SetType(self, type)

Set the type of this field.

This should never be done to a FieldDefn that is already part of an FeatureDefn.

See OGRFieldDefn::SetType().

Parameters:

type (int) -- the new field type.

Examples

>>> f = ogr.FieldDefn()
>>> f.SetType(ogr.OFTReal)
SetUnique(self, bUnique)

Set whether this field has a unique constraint.

By default, fields have no unique constraint, so this method is generally called with TRUE to set a unique constraint.

Drivers that support writing unique constraint will advertise the GDAL_DCAP_UNIQUE_FIELDS driver metadata item.

Note that once a FieldDefn has been added to a layer definition with Layer.AddFieldDefn(), its setter methods should not be called on the object returned with GetLayerDefn().GetFieldDefn(). Instead, Layer::AlterFieldDefn() should be called on a new instance of FieldDefn, for drivers that support Layer.AlterFieldDefn().

See OGRFieldDefn::SetUnique().

Added in version 3.2.

Parameters:

bUnique (bool) -- True if the field must have a unique constraint

SetWidth(self, width)

Set the formatting width for this field in characters.

See OGRFieldDefn::SetWidth().

Parameters:

width (int) -- the new width

property justify

GetJustify(self) -> OGRJustification

Get the justification for this field.

See OGRFieldDefn::GetJustify().

Note: no driver is know to use the concept of field justification.

Returns:

the justification.

Return type:

int

property name

GetName(self) -> char const *

property precision

GetPrecision(self) -> int

Get the formatting precision for this field.

This should normally be zero for fields of types other than OFTReal.

See OGRFieldDefn::GetPrecision().

Returns:

the precision.

Return type:

int

property type

GetType(self) -> OGRFieldType

Fetch type of this field.

See OGRFieldDefn::GetType().

Returns:

field type code, e.g. OFTInteger

Return type:

int

property width

GetWidth(self) -> int

Get the formatting width for this field.

See OGRFieldDefn::GetWidth().

Returns:

the width, zero means no specified width.

Return type:

int

osgeo.ogr.GetFieldSubTypeName(type) char const *

Fetch human readable name for a field subtype.

See OGRFieldDefn::GetFieldSubTypeName().

Parameters:

type (int) -- the field subtype to get name for.

Returns:

the name.

Return type:

str

Examples

>>> ogr.GetFieldSubTypeName(1)
'Boolean'
>>> ogr.GetFieldSubTypeName(ogr.OFSTInt16)
'Int16'
osgeo.ogr.GetFieldTypeName(type) char const *

Fetch human readable name for a field type.

See OGRFieldDefn::GetFieldTypeName().

Parameters:

type (int) -- the field type code to get name for

Returns:

the name

Return type:

str

Examples

>>> ogr.GetFieldTypeName(0)
'Integer'
>>> ogr.GetFieldTypeName(ogr.OFTReal)
'Real'

GeomFieldDefn

class osgeo.ogr.GeomFieldDefn(*args, **kwargs)

Proxy of C++ OGRGeomFieldDefnShadow class.

GetCoordinatePrecision(self) GeomCoordinatePrecision
GetName(self) char const *
GetNameRef(self) char const *
GetSpatialRef(self) SpatialReference
GetType(self) OGRwkbGeometryType
IsIgnored(self) int
IsNullable(self) int
SetCoordinatePrecision(self, coordPrec)
SetIgnored(self, bIgnored)
SetName(self, name)
SetNullable(self, bNullable)
SetSpatialRef(self, srs)
SetType(self, type)
property name

GetName(self) -> char const *

property srs

GetSpatialRef(self) -> SpatialReference

property type

GetType(self) -> OGRwkbGeometryType

FieldDomain

class osgeo.ogr.FieldDomain(*args, **kwargs)

Python proxy of an OGRFieldDomain.

Created using one of:

GetDescription(self) char const *

Get the description of the field domain.

See OGRFieldDomain::GetDescription().

Added in version 3.3.

Returns:

the field domain description (might be empty string).

Return type:

str

GetDomainType(self) OGRFieldDomainType

Get the type of the field domain.

See OGRFieldDomain::GetDomainType().

Added in version 3.3.

Returns:

the type of the field domain.

Return type:

int

Examples

>>> d = ogr.CreateCodedFieldDomain('my_code', None, ogr.OFTInteger, ogr.OFSTNone, { 1 : 'owned', 2 : 'leased' })
>>> d.GetDomainType() == ogr.OFDT_CODED
True
GetEnumeration(self) OGRCodedValue const *

Get the enumeration as a mapping of codes to values.

See OGRCodedFieldDomain::GetEnumeration().

Added in version 3.3.

Return type:

dict

Examples

>>> d = ogr.CreateCodedFieldDomain('my_domain', None, ogr.OFTInteger, ogr.OFSTNone, { 1 : 'owned', 2 : 'leased' })
>>> d.GetEnumeration()
{'1': 'owned', '2': 'leased'}
GetFieldSubType(self) OGRFieldSubType

Get the field subtype of the field domain.

See OGRFieldDomain::GetFieldSubType().

Added in version 3.3.

Returns:

the field subtype of the field domain.

Return type:

int

GetFieldType(self) OGRFieldType

Get the field type of the field domain.

See OGRFieldDomain::GetFieldType().

Added in version 3.3.

Returns:

the field type of the field domain.

Return type:

int

GetGlob(self) char const *

Get the glob expression.

See OGRGlobFieldDomain::GetGlob().

Added in version 3.3.

Returns:

the glob expression, or None in case of error

Return type:

str

GetMaxAsDouble(self) double

Get the maximum value of a range domain.

See OGRRangeFieldDomain::GetMax()

Added in version 3.3.

Returns:

the maximum value of the range

Return type:

float

GetMaxAsString(self) char const *

Get the maximum value of a range domain.

See OGRRangeFieldDomain::GetMax()

Added in version 3.3.

Returns:

the maximum value of the range

Return type:

str

GetMergePolicy(self) OGRFieldDomainMergePolicy

Get the merge policy of the field domain.

See OGRFieldDomain::GetMergePolicy().

Added in version 3.3.

Returns:

the merge policy of the field domain (default = OFDMP_DEFAULT_VALUE)

Return type:

int

GetMinAsDouble(self) double

Get the minimum value of a range domain.

See OGRRangeFieldDomain::GetMin()

Added in version 3.3.

Returns:

the minimum value of the range

Return type:

float

GetMinAsString(self) char const *

Get the minimum value of a range domain.

See OGRRangeFieldDomain::GetMin()

Added in version 3.3.

Returns:

the minimum value of the range

Return type:

str

GetName(self) char const *

Get the name of the field domain.

See OGRFieldDomain::GetName().

Added in version 3.3.

Returns:

the field domain name.

Return type:

str

GetSplitPolicy(self) OGRFieldDomainSplitPolicy

Get the split policy of the field domain.

See OGRFieldDomain::GetSplitPolicy().

Added in version 3.3.

Returns:

the split policy of the field domain (default = OFDSP_DEFAULT_VALUE)

Return type:

int

IsMaxInclusive(self) bool
IsMinInclusive(self) bool
SetMergePolicy(self, policy)

Set the merge policy of the field domain.

See OGRFieldDomain::SetMergePolicy().

Added in version 3.3.

Parameters:

policy (int) -- the merge policy code of the field domain.

SetSplitPolicy(self, policy)

Set the split policy of the field domain.

See OGRFieldDomain::SetSplitPolicy().

Added in version 3.3.

policyint

the split policy code of the field domain.

osgeo.ogr.CreateCodedFieldDomain(name, description, type, subtype, enumeration) FieldDomain

Creates a new coded field domain.

See OGRCodedFieldDomain::OGRCodedFieldDomain().

Added in version 3.3.

Parameters:
  • name (str) -- Domain name. Should not be None.

  • description (str, optional) -- Domain description (can be None)

  • type (int) -- Field type.

  • subtype (int) -- Field subtype.

  • enumeration (dict) -- Enumeration as a dictionary of (code : value) pairs. Should not be None.

Return type:

FieldDomain

osgeo.ogr.CreateGlobFieldDomain(name, description, type, subtype, glob) FieldDomain

Creates a new glob field domain.

See OGRGlobFieldDomain::OGRGlobFieldDomain()

Added in version 3.3.

Parameters:
  • name (str) -- Domain name. Should not be None.

  • description (str, optional) -- Domain description (can be None)

  • type (int) -- Field type.

  • subtype (int) -- Field subtype.

  • glob (str) -- Glob expression. Should not be None.

Return type:

FieldDomain

osgeo.ogr.CreateRangeFieldDomain(name, description, type, subtype, min, minIsInclusive, max, maxIsInclusive) FieldDomain

Creates a new range field domain.

See OGRRangeFieldDomain::OGRRangeFieldDomain().

Added in version 3.3.

Parameters:
  • name (str) -- Domain name. Should not be None.

  • description (str, optional) -- Domain description (can be None)

  • type (int) -- Field type. Generally numeric. Potentially OFTDateTime.

  • subtype (int) -- Field subtype.

  • min (float, optional) -- Minimum value (can be None).

  • minIsInclusive (bool) -- Whether the minimum value is included in the range.

  • max (float, optional) -- Maximum value (can be None).

  • maxIsInclusive (bool) -- Whether the maximum value is included in the range.

Return type:

FieldDomain

Relationship

class osgeo.gdal.Relationship(*args)

Proxy of C++ GDALRelationshipShadow class.

GetBackwardPathLabel(self) char const *
GetCardinality(self) GDALRelationshipCardinality
GetForwardPathLabel(self) char const *
GetLeftMappingTableFields(self) char **
GetLeftTableFields(self) char **
GetLeftTableName(self) char const *
GetMappingTableName(self) char const *
GetName(self) char const *
GetRelatedTableType(self) char const *
GetRightMappingTableFields(self) char **
GetRightTableFields(self) char **
GetRightTableName(self) char const *
GetType(self) GDALRelationshipType
SetBackwardPathLabel(self, pszLabel)
SetForwardPathLabel(self, pszLabel)
SetLeftMappingTableFields(self, pFields)
SetLeftTableFields(self, pFields)
SetMappingTableName(self, pszName)
SetRelatedTableType(self, pszType)
SetRightMappingTableFields(self, pFields)
SetRightTableFields(self, pFields)
SetType(self, type)

StyleTable

class osgeo.ogr.StyleTable(*args)

Proxy of C++ OGRStyleTableShadow class.

AddStyle(self, pszName, pszStyleString) int
Find(self, pszName) char const *
GetLastStyleName(self) char const *
GetNextStyle(self) char const *
LoadStyleTable(self, utf8_string) int
ResetStyleStringReading(self)
SaveStyleTable(self, utf8_string) int