[Gdal-dev] Writing shapefiles with ogr for qgis

Frank Warmerdam warmerdam at pobox.com
Tue Apr 27 19:45:55 EDT 2004


Tim Sutton wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Hi
> 
> Can someone point me to a short code sample on writing a shapefile using ogr. 
> Currently I have written stuff using Franks shapelib, but am wondering if ogr 
> is better suited to this purpose in that:
> 
> a) qgis already has gdal/ogr deps
> b) ogr provides a c++ interface

Tim,

It seems there is no OGR API Tutorial.  I would encourage you to review the
OGR Architecture document for general information on OGR:

   http://www.remotesensing.org/gdal/ogr/ogr_arch.html

The gdal/ogr/ogr2ogr.cpp program is a respectible example of how to use
OGR to write files, though it is a bit complicated since it tries to do alot
of things during translation.

The general idea is you need to following the following steps:

  o Register driver(s) (at least the Shapefile driver).
  o Get the driver - OGRSFDriverRegistrar::GetDriverByName().
  o Create the shapefile (OGRSFDriver::CreateDataSource()).  You can give the
    name of the shapefile (with .shp extension) to create a single file.
    Otherwise the shapefile driver will create a directory, and a file set for
    each layer.
  o Create the desired layer (OGRDataSource::CreateLayer() - the layer name
    should likely match the basename of the shapefile you created before).
    Set the geometry type to determine the file type you want to create.
  o Create all the fields you want for the layer with OGRLayer::CreateField().
  o For each feature to be written, create a feature with OGRFeature::CreateFeature(),
    passing in the layer definition from the layer.
  o Assign each attribute to the feature in turn.
  o Create a geometry and assign it to the feature.  There are various methods
    for geometry construction depending on what you want.
  o Write the feature to the file with the OGRLayer::CreateFeature() method.
  o Delete your copy of the feature (ie. with OGRFeature::DestroyFeature()).
  o Make sure you delete the datasource when you are done to ensure it is
    properly closed and flushed to disk.

If you only ever want to write to shapefiles, using OGR won't give you any
substantial advantages, but assuming you are interested in writing other
formats too, it should be a useful step.

Best regards,
-- 
---------------------------------------+--------------------------------------
I set the clouds in motion - turn up   | Frank Warmerdam, warmerdam at pobox.com
light and sound - activate the windows | http://pobox.com/~warmerdam
and watch the world go round - Rush    | Geospatial Programmer for Rent




More information about the Gdal-dev mailing list