This document is intended to document using the OGR C++ classes to read and write data from a file. It is strongly advised that the read first review the OGR Architecture document describing the key classes and their roles in OGR.
It also includes code snippets for the corresponding functions in C and Python.
Reading From OGR
For purposes of demonstrating reading with OGR, we will construct a small utility for dumping point layers from an OGR data source to stdout in comma-delimited format.
Initially it is necessary to register all the format drivers that are desired. This is normally accomplished by calling GDALAllRegister() which registers all format drivers built into GDAL/OGR.
In C++ :
int main()
{
void GDALAllRegister(void)
Register all known configured GDAL drivers.
Definition: gdalallregister.cpp:62
Classes related to registration of format support, and opening datasets.
In C :
int main()
{
Public (C callable) GDAL entry points.
Next we need to open the input OGR datasource. Datasources can be files, RDBMSes, directories full of files, or even remote web services depending on the driver being used. However, the datasource name is always a single string. In this case we are hardcoded to open a particular shapefile. The second argument (GDAL_OF_VECTOR) tells the OGROpen() method that we want a vector driver to be use and that don't require update access. On failure NULL is returned, and we report an error.
In C++ :
if( poDS == NULL )
{
printf( "Open failed.\n" );
exit( 1 );
}
A set of associated raster bands, usually from one file.
Definition: gdal_priv.h:336
#define GDAL_OF_VECTOR
Allow vector drivers to be used.
Definition: gdal.h:448
GDALDatasetH GDALOpenEx(const char *pszFilename, unsigned int nOpenFlags, const char *const *papszAllowedDrivers, const char *const *papszOpenOptions, const char *const *papszSiblingFiles) CPL_WARN_UNUSED_RESULT
Open a raster or vector file as a GDALDataset.
Definition: gdaldataset.cpp:3206
In C :
if( hDS == NULL )
{
printf( "Open failed.\n" );
exit( 1 );
}
void * GDALDatasetH
Opaque type used for the C bindings of the C++ GDALDataset class.
Definition: gdal.h:255
A GDALDataset can potentially have many layers associated with it. The number of layers available can be queried with GDALDataset::GetLayerCount() and individual layers fetched by index using GDALDataset::GetLayer(). However, we will just fetch the layer by name.
In C++ :
virtual OGRLayer * GetLayerByName(const char *)
Fetch a layer by name.
Definition: gdaldataset.cpp:5179
This class represents a layer of simple features, with access methods.
Definition: ogrsf_frmts.h:71
In C :
OGRLayerH GDALDatasetGetLayerByName(GDALDatasetH, const char *)
Fetch a layer by name.
Definition: gdaldataset.cpp:4240
void * OGRLayerH
Opaque type for a layer (OGRLayer)
Definition: ogr_api.h:509
Now we want to start reading features from the layer. Before we start we could assign an attribute or spatial filter to the layer to restrict the set of feature we get back, but for now we are interested in getting all features.
With GDAL 2.3 and C++11:
for( auto& poFeature: poLayer )
{
With GDAL 2.3 and C:
{
#define OGR_FOR_EACH_FEATURE_BEGIN(hFeat, hLayer)
Conveniency macro to iterate over features of a layer.
Definition: ogr_api.h:561
If using older GDAL versions, while it isn't strictly necessary in this circumstance since we are starting fresh with the layer, it is often wise to call OGRLayer::ResetReading() to ensure we are starting at the beginning of the layer. We iterate through all the features in the layer using OGRLayer::GetNextFeature(). It will return NULL when we run out of features.
With GDAL < 2.3 and C++ :
poLayer->ResetReading();
while( (poFeature = poLayer->GetNextFeature()) != NULL )
{
A simple feature, including geometry and attributes.
Definition: ogr_feature.h:355
With GDAL < 2.3 and C :
{
OGRFeatureH OGR_L_GetNextFeature(OGRLayerH) CPL_WARN_UNUSED_RESULT
Fetch the next available feature from this layer.
Definition: ogrlayer.cpp:541
void * OGRFeatureH
Opaque type for a feature (OGRFeature)
Definition: ogr_api.h:302
void OGR_L_ResetReading(OGRLayerH)
Reset feature reading to start on the first feature.
Definition: ogrlayer.cpp:1473
In order to dump all the attribute fields of the feature, it is helpful to get the OGRFeatureDefn. This is an object, associated with the layer, containing the definitions of all the fields. We loop over all the fields, and fetch and report the attributes based on their type.
With GDAL 2.3 and C++11:
for( auto&& oField: *poFeature )
{
switch( oField.GetType() )
{
printf( "%d,", oField.GetInteger() );
break;
break;
printf( "%.3f,", oField.GetDouble() );
break;
printf( "%s,", oField.GetString() );
break;
default:
printf( "%s,", oField.GetAsString() );
break;
}
}
#define CPL_FRMT_GIB
Printf formatting for GIntBig.
Definition: cpl_port.h:316
@ OFTInteger
Simple 32bit integer.
Definition: ogr_core.h:596
@ OFTString
String of ASCII chars.
Definition: ogr_core.h:600
@ OFTReal
Double Precision floating point.
Definition: ogr_core.h:598
@ OFTInteger64
Single 64bit integer.
Definition: ogr_core.h:608
With GDAL < 2.3 and C++ :
for(
int iField = 0; iField < poFDefn->
GetFieldCount(); iField++ )
{
{
printf( "%d,", poFeature->GetFieldAsInteger( iField ) );
break;
printf(
CPL_FRMT_GIB ",", poFeature->GetFieldAsInteger64( iField ) );
break;
printf( "%.3f,", poFeature->GetFieldAsDouble(iField) );
break;
printf( "%s,", poFeature->GetFieldAsString(iField) );
break;
default:
printf( "%s,", poFeature->GetFieldAsString(iField) );
break;
}
}
Definition of a feature class or feature layer.
Definition: ogr_feature.h:260
virtual int GetFieldCount() const
Fetch number of fields on this feature.
Definition: ogrfeaturedefn.cpp:286
virtual OGRFieldDefn * GetFieldDefn(int i)
Fetch field definition.
Definition: ogrfeaturedefn.cpp:330
Definition of an attribute of an OGRFeatureDefn.
Definition: ogr_feature.h:93
OGRFieldType GetType() const
Fetch type of this field.
Definition: ogr_feature.h:115
In C :
int iField;
{
{
break;
break;
break;
break;
default:
break;
}
}
GIntBig OGR_F_GetFieldAsInteger64(OGRFeatureH, int)
Fetch field value as integer 64 bit.
Definition: ogrfeature.cpp:2077
OGRFieldDefnH OGR_FD_GetFieldDefn(OGRFeatureDefnH, int)
Fetch field definition of the passed feature definition.
Definition: ogrfeaturedefn.cpp:385
int OGR_FD_GetFieldCount(OGRFeatureDefnH)
Fetch number of fields on the passed feature definition.
Definition: ogrfeaturedefn.cpp:304
double OGR_F_GetFieldAsDouble(OGRFeatureH, int)
Fetch field value as a double.
Definition: ogrfeature.cpp:2190
void * OGRFieldDefnH
Opaque type for a field definition (OGRFieldDefn)
Definition: ogr_api.h:298
const char * OGR_F_GetFieldAsString(OGRFeatureH, int)
Fetch field value as a string.
Definition: ogrfeature.cpp:2650
OGRFeatureDefnH OGR_L_GetLayerDefn(OGRLayerH)
Fetch the schema information for this layer.
Definition: ogrlayer.cpp:993
void * OGRFeatureDefnH
Opaque type for a feature definition (OGRFeatureDefn)
Definition: ogr_api.h:300
int OGR_F_GetFieldAsInteger(OGRFeatureH, int)
Fetch field value as integer.
Definition: ogrfeature.cpp:1956
OGRFieldType OGR_Fld_GetType(OGRFieldDefnH)
Fetch type of this field.
Definition: ogrfielddefn.cpp:251
There are a few more field types than those explicitly handled above, but a reasonable representation of them can be fetched with the OGRFeature::GetFieldAsString() method. In fact we could shorten the above by using OGRFeature::GetFieldAsString() for all the types.
Next we want to extract the geometry from the feature, and write out the point geometry x and y. Geometries are returned as a generic OGRGeometry pointer. We then determine the specific geometry type, and if it is a point, we cast it to point and operate on it. If it is something else we write placeholders.
In C++ :
poGeometry = poFeature->GetGeometryRef();
if( poGeometry != NULL
{
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,3,0)
#else
#endif
printf(
"%.3f,%3.f\n", poPoint->
getX(), poPoint->
getY() );
}
else
{
printf( "no point geometry\n" );
}
Abstract base class for all geometry classes.
Definition: ogr_geometry.h:287
OGRPoint * toPoint()
Down-cast to OGRPoint*.
Definition: ogr_geometry.h:524
virtual OGRwkbGeometryType getGeometryType() const =0
Fetch geometry type.
Point class.
Definition: ogr_geometry.h:811
double getX() const
Return x.
Definition: ogr_geometry.h:853
double getY() const
Return y.
Definition: ogr_geometry.h:855
#define wkbFlatten(x)
Return the 2D geometry type corresponding to the specified geometry type.
Definition: ogr_core.h:440
@ wkbPoint
0-dimensional geometric object, standard WKB
Definition: ogr_core.h:321
In C :
if( hGeometry != NULL
{
}
else
{
printf( "no point geometry\n" );
}
void * OGRGeometryH
Opaque type for a geometry.
Definition: ogr_api.h:60
OGRGeometryH OGR_F_GetGeometryRef(OGRFeatureH)
Fetch an handle to feature geometry.
Definition: ogrfeature.cpp:628
double OGR_G_GetX(OGRGeometryH, int)
Fetch the x coordinate of a point from a geometry.
Definition: ogr_api.cpp:187
double OGR_G_GetY(OGRGeometryH, int)
Fetch the x coordinate of a point from a geometry.
Definition: ogr_api.cpp:210
OGRwkbGeometryType OGR_G_GetGeometryType(OGRGeometryH)
Fetch geometry type.
Definition: ogrgeometry.cpp:1839
The wkbFlatten() macro is used above to convert the type for a wkbPoint25D (a point with a z coordinate) into the base 2D geometry type code (wkbPoint). For each 2D geometry type there is a corresponding 2.5D type code. The 2D and 2.5D geometry cases are handled by the same C++ class, so our code will handle 2D or 3D cases properly.
Starting with OGR 1.11, several geometry fields can be associated to a feature.
In C++ :
int iGeomField;
int nGeomFieldCount;
nGeomFieldCount = poFeature->GetGeomFieldCount();
for(iGeomField = 0; iGeomField < nGeomFieldCount; iGeomField ++ )
{
poGeometry = poFeature->GetGeomFieldRef(iGeomField);
if( poGeometry != NULL
{
#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,3,0)
#else
#endif
printf(
"%.3f,%3.f\n", poPoint->
getX(), poPoint->
getY() );
}
else
{
printf( "no point geometry\n" );
}
}
In C :
int iGeomField;
int nGeomFieldCount;
for(iGeomField = 0; iGeomField < nGeomFieldCount; iGeomField ++ )
{
if( hGeometry != NULL
{
}
else
{
printf( "no point geometry\n" );
}
}
OGRGeometryH OGR_F_GetGeomFieldRef(OGRFeatureH hFeat, int iField)
Fetch an handle to feature geometry.
Definition: ogrfeature.cpp:755
int OGR_F_GetGeomFieldCount(OGRFeatureH hFeat)
Fetch number of geometry fields on this feature This will always be the same as the geometry field co...
Definition: ogrfeature.cpp:1233
In Python:
nGeomFieldCount = feat.GetGeomFieldCount()
for iGeomField in range(nGeomFieldCount):
geom = feat.GetGeomFieldRef(iGeomField)
if geom is not None and geom.GetGeometryType() == ogr.
wkbPoint:
print "%.3f, %.3f" % ( geom.GetX(), geom.GetY() )
else:
print "no point geometry\n"
Note that OGRFeature::GetGeometryRef() and OGRFeature::GetGeomFieldRef() return a pointer to the internal geometry owned by the OGRFeature. There we don't actually deleted the return geometry.
With GDAL 2.3 and C++11, the looping over features is simply terminated by a closing curly bracket.
With GDAL 2.3 and C, the looping over features is simply terminated by the following.
}
#define OGR_FOR_EACH_FEATURE_END(hFeat)
End of iterator.
Definition: ogr_api.h:574
For GDAL < 2.3, as the OGRLayer::GetNextFeature() method returns a copy of the feature that is now owned by us. So at the end of use we must free the feature. We could just "delete" it, but this can cause problems in windows builds where the GDAL DLL has a different "heap" from the main program. To be on the safe side we use a GDAL function to delete the feature.
In C++ :
}
static void DestroyFeature(OGRFeature *)
Destroy feature.
Definition: ogrfeature.cpp:282
In C :
}
void OGR_F_Destroy(OGRFeatureH)
Destroy feature.
Definition: ogrfeature.cpp:220
The OGRLayer returned by GDALDataset::GetLayerByName() is also a reference to an internal layer owned by the GDALDataset so we don't need to delete it. But we do need to delete the datasource in order to close the input file. Once again we do this with a custom delete method to avoid special win32 heap issues.
In C/C++ :
}
void GDALClose(GDALDatasetH)
Close GDAL dataset.
Definition: gdaldataset.cpp:3588
All together our program looks like this.
With GDAL 2.3 and C++11 :
int main()
{
if( poDS == nullptr )
{
printf( "Open failed.\n" );
exit( 1 );
}
{
for( const auto& poFeature: *poLayer )
{
for( const auto& oField: *poFeature )
{
switch( oField.GetType() )
{
printf( "%d,", oField.GetInteger() );
break;
break;
printf( "%.3f,", oField.GetDouble() );
break;
printf( "%s,", oField.GetString() );
break;
default:
printf( "%s,", oField.GetAsString() );
break;
}
}
const OGRGeometry *poGeometry = poFeature->GetGeometryRef();
if( poGeometry != nullptr
{
printf(
"%.3f,%3.f\n", poPoint->
getX(), poPoint->
getY() );
}
else
{
printf( "no point geometry\n" );
}
}
}
return 0;
}
static GDALDataset * Open(const char *pszFilename, unsigned int nOpenFlags=0, const char *const *papszAllowedDrivers=nullptr, const char *const *papszOpenOptions=nullptr, const char *const *papszSiblingFiles=nullptr)
Definition: gdal_priv.h:613
Layers GetLayers()
Function that returns an iterable object over layers in the dataset.
Definition: gdaldataset.cpp:7693
std::unique_ptr< GDALDataset, GDALDatasetUniquePtrDeleter > GDALDatasetUniquePtr
Unique pointer type for GDALDataset.
Definition: gdal_priv.h:839
In C++ :
int main()
{
if( poDS == NULL )
{
printf( "Open failed.\n" );
exit( 1 );
}
{
for(
int iField = 0; iField < poFDefn->
GetFieldCount(); iField++ )
{
{
break;
break;
break;
break;
default:
break;
}
}
if( poGeometry != NULL
{
printf(
"%.3f,%3.f\n", poPoint->
getX(), poPoint->
getY() );
}
else
{
printf( "no point geometry\n" );
}
}
}
GIntBig GetFieldAsInteger64(int i) const
Fetch field value as integer 64 bit.
Definition: ogrfeature.cpp:1998
const char * GetFieldAsString(int i) const
Fetch field value as a string.
Definition: ogrfeature.cpp:2297
int GetFieldAsInteger(int i) const
Fetch field value as integer.
Definition: ogrfeature.cpp:1859
OGRGeometry * GetGeometryRef()
Fetch pointer to feature geometry.
Definition: ogrfeature.cpp:583
double GetFieldAsDouble(int i) const
Fetch field value as a double.
Definition: ogrfeature.cpp:2116
virtual OGRFeature * GetNextFeature() CPL_WARN_UNUSED_RESULT=0
Fetch the next available feature from this layer.
virtual OGRFeatureDefn * GetLayerDefn()=0
Fetch the schema information for this layer.
virtual void ResetReading()=0
Reset feature reading to start on the first feature.
In C :
int main()
{
if( hDS == NULL )
{
printf( "Open failed.\n" );
exit( 1 );
}
{
int iField;
{
{
break;
break;
break;
break;
default:
break;
}
}
if( hGeometry != NULL
{
}
else
{
printf( "no point geometry\n" );
}
}
}
In Python:
import sys
from osgeo import gdal
ds = gdal.OpenEx( "point.shp", gdal.OF_VECTOR )
if ds is None:
print "Open failed.\n"
sys.exit( 1 )
lyr = ds.GetLayerByName( "point" )
lyr.ResetReading()
for feat in lyr:
feat_defn = lyr.GetLayerDefn()
for i in range(feat_defn.GetFieldCount()):
field_defn = feat_defn.GetFieldDefn(i)
# Tests below can be simplified with just :
# print feat.GetField(i)
print "%d" % feat.GetFieldAsInteger64(i)
elif field_defn.GetType() == ogr.
OFTReal:
print "%.3f" % feat.GetFieldAsDouble(i)
print "%s" % feat.GetFieldAsString(i)
else:
print "%s" % feat.GetFieldAsString(i)
geom = feat.GetGeometryRef()
if geom is not None and geom.GetGeometryType() == ogr.
wkbPoint:
print "%.3f, %.3f" % ( geom.GetX(), geom.GetY() )
else:
print "no point geometry\n"
ds = None
Writing To OGR
As an example of writing through OGR, we will do roughly the opposite of the above. A short program that reads comma separated values from input text will be written to a point shapefile via OGR.
As usual, we start by registering all the drivers, and then fetch the Shapefile driver as we will need it to create our output file.
In C++ :
int main()
{
const char *pszDriverName = "ESRI Shapefile";
if( poDriver == NULL )
{
printf( "%s driver not available.\n", pszDriverName );
exit( 1 );
}
GDALDriver * GetDriverByName(const char *)
Fetch a driver based on the short name.
Definition: gdaldrivermanager.cpp:590
Format specific driver.
Definition: gdal_priv.h:1424
GDALDriverManager * GetGDALDriverManager(void)
Fetch the global GDAL driver manager.
Definition: gdaldrivermanager.cpp:97
In C :
int main()
{
const char *pszDriverName = "ESRI Shapefile";
if( poDriver == NULL )
{
printf( "%s driver not available.\n", pszDriverName );
exit( 1 );
}
GDALDriverH GDALGetDriverByName(const char *)
Fetch a driver based on the short name.
Definition: gdaldrivermanager.cpp:612
C API and defines for OGRFeature, OGRGeometry, and OGRDataSource related classes.
Next we create the datasource. The ESRI Shapefile driver allows us to create a directory full of shapefiles, or a single shapefile as a datasource. In this case we will explicitly create a single file by including the extension in the name. Other drivers behave differently. The second, third, fourth and fifth argument are related to raster dimensions (in case the driver has raster capabilities). The last argument to the call is a list of option values, but we will just be using defaults in this case. Details of the options supported are also format specific.
In C ++ :
if( poDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
GDALDataset * Create(const char *pszName, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszOptions) CPL_WARN_UNUSED_RESULT
Create a new dataset with this driver.
Definition: gdaldriver.cpp:162
@ GDT_Unknown
Definition: gdal.h:61
In C :
if( hDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
GDALDatasetH GDALCreate(GDALDriverH hDriver, const char *, int, int, int, GDALDataType, CSLConstList) CPL_WARN_UNUSED_RESULT
Create a new dataset with this driver.
Definition: gdaldriver.cpp:306
Now we create the output layer. In this case since the datasource is a single file, we can only have one layer. We pass wkbPoint to specify the type of geometry supported by this layer. In this case we aren't passing any coordinate system information or other special layer creation options.
In C++ :
if( poLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
virtual OGRLayer * CreateLayer(const char *pszName, OGRSpatialReference *poSpatialRef=nullptr, OGRwkbGeometryType eGType=wkbUnknown, char **papszOptions=nullptr)
This method attempts to create a new layer on the dataset with the indicated name,...
Definition: gdaldataset.cpp:4341
In C :
if( hLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
OGRLayerH GDALDatasetCreateLayer(GDALDatasetH, const char *, OGRSpatialReferenceH, OGRwkbGeometryType, CSLConstList)
This function attempts to create a new layer on the dataset with the indicated name,...
Definition: gdaldataset.cpp:4428
Now that the layer exists, we need to create any attribute fields that should appear on the layer. Fields must be added to the layer before any features are written. To create a field we initialize an OGRField object with the information about the field. In the case of Shapefiles, the field width and precision is significant in the creation of the output .dbf file, so we set it specifically, though generally the defaults are OK. For this example we will just have one attribute, a name string associated with the x,y point.
Note that the template OGRField we pass to CreateField() is copied internally. We retain ownership of the object.
In C++:
oField.SetWidth(32);
{
printf( "Creating Name field failed.\n" );
exit( 1 );
}
virtual OGRErr CreateField(OGRFieldDefn *poField, int bApproxOK=TRUE)
Create a new field on a layer.
Definition: ogrlayer.cpp:665
#define OGRERR_NONE
Success.
Definition: ogr_core.h:292
In C:
{
printf( "Creating Name field failed.\n" );
exit( 1 );
}
void OGR_Fld_SetWidth(OGRFieldDefnH, int)
Set the formatting width for this field in characters.
Definition: ogrfielddefn.cpp:908
OGRFieldDefnH OGR_Fld_Create(const char *, OGRFieldType) CPL_WARN_UNUSED_RESULT
Create a new field definition.
Definition: ogrfielddefn.cpp:113
void OGR_Fld_Destroy(OGRFieldDefnH)
Destroy a field definition.
Definition: ogrfielddefn.cpp:139
OGRErr OGR_L_CreateField(OGRLayerH, OGRFieldDefnH, int)
Create a new field on a layer.
Definition: ogrlayer.cpp:681
The following snipping loops reading lines of the form "x,y,name" from stdin, and parsing them.
In C++ and in C :
double x, y;
char szName[33];
while( !feof(stdin)
&& fscanf( stdin, "%lf,%lf,%32s", &x, &y, szName ) == 3 )
{
To write a feature to disk, we must create a local OGRFeature, set attributes and attach geometry before trying to write it to the layer. It is imperative that this feature be instantiated from the OGRFeatureDefn associated with the layer it will be written to.
In C++ :
static OGRFeature * CreateFeature(OGRFeatureDefn *)
Feature factory.
Definition: ogrfeature.cpp:246
void SetField(int i, int nValue)
Set field to integer value.
Definition: ogrfeature.cpp:3415
In C :
OGRFeatureH OGR_F_Create(OGRFeatureDefnH) CPL_WARN_UNUSED_RESULT
Feature factory.
Definition: ogrfeature.cpp:129
int OGR_F_GetFieldIndex(OGRFeatureH, const char *)
Fetch the field index given field name.
Definition: ogrfeature.cpp:1190
void OGR_F_SetFieldString(OGRFeatureH, int, const char *)
Set field to string value.
Definition: ogrfeature.cpp:4131
We create a local geometry object, and assign its copy (indirectly) to the feature. The OGRFeature::SetGeometryDirectly() differs from OGRFeature::SetGeometry() in that the direct method gives ownership of the geometry to the feature. This is generally more efficient as it avoids an extra deep object copy of the geometry.
In C++ :
OGRErr SetGeometry(const OGRGeometry *)
Set feature geometry.
Definition: ogrfeature.cpp:437
void setX(double xIn)
Set x.
Definition: ogr_geometry.h:866
void setY(double yIn)
Set y.
Definition: ogr_geometry.h:870
In C :
OGRGeometryH OGR_G_CreateGeometry(OGRwkbGeometryType) CPL_WARN_UNUSED_RESULT
Create an empty geometry of desired type.
Definition: ogrgeometryfactory.cpp:605
OGRErr OGR_F_SetGeometry(OGRFeatureH, OGRGeometryH)
Set feature geometry.
Definition: ogrfeature.cpp:472
void OGR_G_SetPoint_2D(OGRGeometryH, int iPoint, double, double)
Set the location of a vertex in a point or linestring geometry.
Definition: ogr_api.cpp:878
void OGR_G_DestroyGeometry(OGRGeometryH)
Destroy geometry object.
Definition: ogrgeometryfactory.cpp:648
Now we create a feature in the file. The OGRLayer::CreateFeature() does not take ownership of our feature so we clean it up when done with it.
In C++ :
{
printf( "Failed to create feature in shapefile.\n" );
exit( 1 );
}
}
OGRErr CreateFeature(OGRFeature *poFeature) CPL_WARN_UNUSED_RESULT
Create and write a new feature within a layer.
Definition: ogrlayer.cpp:626
In C :
{
printf( "Failed to create feature in shapefile.\n" );
exit( 1 );
}
}
OGRErr OGR_L_CreateFeature(OGRLayerH, OGRFeatureH) CPL_WARN_UNUSED_RESULT
Create and write a new feature within a layer.
Definition: ogrlayer.cpp:647
Finally we need to close down the datasource in order to ensure headers are written out in an orderly way and all resources are recovered.
In C/C++ :
The same program all in one block looks like this:
In C++ :
int main()
{
const char *pszDriverName = "ESRI Shapefile";
if( poDriver == NULL )
{
printf( "%s driver not available.\n", pszDriverName );
exit( 1 );
}
if( poDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
if( poLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
oField.SetWidth(32);
{
printf( "Creating Name field failed.\n" );
exit( 1 );
}
double x, y;
char szName[33];
while( !feof(stdin)
&& fscanf( stdin, "%lf,%lf,%32s", &x, &y, szName ) == 3 )
{
{
printf( "Failed to create feature in shapefile.\n" );
exit( 1 );
}
}
}
In C :
int main()
{
const char *pszDriverName = "ESRI Shapefile";
double x, y;
char szName[33];
if( hDriver == NULL )
{
printf( "%s driver not available.\n", pszDriverName );
exit( 1 );
}
if( hDS == NULL )
{
printf( "Creation of output file failed.\n" );
exit( 1 );
}
if( hLayer == NULL )
{
printf( "Layer creation failed.\n" );
exit( 1 );
}
{
printf( "Creating Name field failed.\n" );
exit( 1 );
}
while( !feof(stdin)
&& fscanf( stdin, "%lf,%lf,%32s", &x, &y, szName ) == 3 )
{
{
printf( "Failed to create feature in shapefile.\n" );
exit( 1 );
}
}
}
void * GDALDriverH
Opaque type used for the C bindings of the C++ GDALDriver class.
Definition: gdal.h:261
In Python :
import sys
from osgeo import gdal
from osgeo import ogr
import string
driverName = "ESRI Shapefile"
drv = gdal.GetDriverByName( driverName )
if drv is None:
print "%s driver not available.\n" % driverName
sys.exit( 1 )
ds = drv.Create( "point_out.shp", 0, 0, 0, gdal.GDT_Unknown )
if ds is None:
print "Creation of output file failed.\n"
sys.exit( 1 )
lyr = ds.CreateLayer( "point_out", None, ogr.wkbPoint )
if lyr is None:
print "Layer creation failed.\n"
sys.exit( 1 )
field_defn = ogr.FieldDefn( "Name", ogr.OFTString )
field_defn.SetWidth( 32 )
if lyr.CreateField ( field_defn ) != 0:
print "Creating Name field failed.\n"
sys.exit( 1 )
# Expected format of user input: x y name
linestring = raw_input()
linelist = string.split(linestring)
while len(linelist) == 3:
x = float(linelist[0])
y = float(linelist[1])
name = linelist[2]
feat = ogr.Feature( lyr.GetLayerDefn())
feat.SetField( "Name", name )
pt.SetPoint_2D(0, x, y)
feat.SetGeometry(pt)
if lyr.CreateFeature(feat) != 0:
print "Failed to create feature in shapefile.\n"
sys.exit( 1 )
feat.Destroy()
linestring = raw_input()
linelist = string.split(linestring)
ds = None
Starting with OGR 1.11, several geometry fields can be associated to a feature. This capability is just available for a few file formats, such as PostGIS.
To create such datasources, geometry fields must be first created. Spatial reference system objects can be associated to each geometry field.
In C++ :
oPointField.SetSpatialRef(poSRS);
{
printf( "Creating field PointField failed.\n" );
exit( 1 );
}
oPointField2.SetSpatialRef(poSRS);
{
printf( "Creating field PointField2 failed.\n" );
exit( 1 );
}
Definition of a geometry field of an OGRFeatureDefn.
Definition: ogr_feature.h:183
virtual OGRErr CreateGeomField(OGRGeomFieldDefn *poField, int bApproxOK=TRUE)
Create a new geometry field on a layer.
Definition: ogrlayer.cpp:876
This class represents an OpenGIS Spatial Reference System, and contains methods for converting betwee...
Definition: ogr_spatialref.h:157
OGRErr importFromEPSG(int)
Initialize SRS based on EPSG geographic, projected or vertical CRS code.
Definition: ogrspatialreference.cpp:10220
void Release()
Decrements the reference count by one, and destroy if zero.
Definition: ogrspatialreference.cpp:931
In C :
{
printf( "Creating field PointField failed.\n" );
exit( 1 );
}
{
printf( "Creating field PointField2 failed.\n" );
exit( 1 );
}
void OGR_GFld_Destroy(OGRGeomFieldDefnH)
Destroy a geometry field definition.
Definition: ogrgeomfielddefn.cpp:155
void * OGRSpatialReferenceH
Opaque type for a spatial reference system.
Definition: ogr_api.h:74
OGRGeomFieldDefnH OGR_GFld_Create(const char *, OGRwkbGeometryType) CPL_WARN_UNUSED_RESULT
Create a new field geometry definition.
Definition: ogrgeomfielddefn.cpp:109
void OGR_GFld_SetSpatialRef(OGRGeomFieldDefnH, OGRSpatialReferenceH hSRS)
Set the spatial reference of this field.
Definition: ogrgeomfielddefn.cpp:517
struct OGRGeomFieldDefnHS * OGRGeomFieldDefnH
Opaque type for a geometry field definition (OGRGeomFieldDefn)
Definition: ogr_api.h:307
OGRErr OGR_L_CreateGeomField(OGRLayerH hLayer, OGRGeomFieldDefnH hFieldDefn, int bForce)
Create a new geometry field on a layer.
Definition: ogrlayer.cpp:892
OGRErr OSRImportFromEPSG(OGRSpatialReferenceH, int)
Initialize SRS based on EPSG geographic, projected or vertical CRS code.
Definition: ogrspatialreference.cpp:10236
OGRSpatialReferenceH OSRNewSpatialReference(const char *)
Constructor.
Definition: ogrspatialreference.cpp:689
void OSRRelease(OGRSpatialReferenceH)
Decrements the reference count by one, and destroy if zero.
Definition: ogrspatialreference.cpp:947
To write a feature to disk, we must create a local OGRFeature, set attributes and attach geometries before trying to write it to the layer. It is imperative that this feature be instantiated from the OGRFeatureDefn associated with the layer it will be written to.
In C++ :
char* pszWKT;
pszWKT = (char*) "POINT (2 49)";
pszWKT = (char*) "POINT (500000 4500000)";
{
printf( "Failed to create feature.\n" );
exit( 1 );
}
OGRErr SetGeomFieldDirectly(int iField, OGRGeometry *)
Set feature geometry of a specified geometry field.
Definition: ogrfeature.cpp:802
static OGRErr createFromWkt(const char *, OGRSpatialReference *, OGRGeometry **)
Create a geometry object of the appropriate type from its well known text representation.
Definition: ogrgeometryfactory.cpp:464
In C :
char* pszWKT;
pszWKT = (char*) "POINT (2 49)";
pszWKT = (char*) "POINT (500000 4500000)";
{
printf( "Failed to create feature.\n" );
exit( 1 );
}
OGRErr OGR_F_SetGeomFieldDirectly(OGRFeatureH hFeat, int iField, OGRGeometryH hGeom)
Set feature geometry of a specified geometry field.
Definition: ogrfeature.cpp:845
int OGR_F_GetGeomFieldIndex(OGRFeatureH hFeat, const char *pszName)
Fetch the geometry field index given geometry field name.
Definition: ogrfeature.cpp:1344
OGRErr OGR_G_CreateFromWkt(char **, OGRSpatialReferenceH, OGRGeometryH *)
Create a geometry object of the appropriate type from its well known text representation.
Definition: ogrgeometryfactory.cpp:497
In Python :
feat = ogr.Feature( lyr.GetLayerDefn() )
feat.SetGeomFieldDirectly( "PointField",
ogr.CreateGeometryFromWkt( "POINT (2 49)" ) )
feat.SetGeomFieldDirectly( "PointField2",
ogr.CreateGeometryFromWkt( "POINT (500000 4500000)" ) )
if lyr.CreateFeature( feat ) != 0 )
{
print( "Failed to create feature.\n" );
sys.exit( 1 );
}