'GDAL CreateFeature doesn't add a Feature to the Layer

I'm running Python 2.7 on Ubuntu 17.10, with osgeo v2.2.1 installed via apt.

My code loads osgeo and 1) tries to create a shapefile with 1 layer and 1 field, 2) create a polygon (4 points geometry), then 3) add the polygon to the shapefile's layer. Everything runs without trouble until the third function when I use layer.CreateFeature(feature) :

driver = ogr.GetDriverByName('ESRI Shapefile')
ds = driver.Open(shapefile_name,-1)
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
layer = ds.GetLayer()
print "layer",layer,", number of features :",layer.GetFeatureCount()

This prints :

layer <osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x7f79aa499c90> > , number of features : 0

I then create a geometry from the polygon I already created and passed to the function beforehand :

defn = layer.GetLayerDefn()

geom = ogr.CreateGeometryFromWkb(poly)
print "geom",geom

This prints :

geom POLYGON ((-106 24 0,-100 26 0,-103 20 0,-106 20 0))

Code then goes on to create the feature :

feat = ogr.Feature(defn)
feat.SetField('polygon_id', polygon_name)
feat.SetGeometry(geom)
print feat
print "Created feature",feat.GetField('polygon_id')

This feature is created :

<osgeo.ogr.Feature; proxy of <Swig Object of type 'OGRFeatureShadow *' at 0x7f35cd988d50> >
Created feature polygon_1

But when I add it to the layer, nothing happens :

layer.CreateFeature(feat)
print "number of features : ",layer.GetFeatureCount()

Prints :

number of features :  0

What did I miss ?



Solution 1:[1]

The vector tutorial in the gdal documentation provides a good example for writing a wkbPoint feature, but writing a wkbPolygon feature is a little trickier. Below is (c++) code works for me. (Note: TMultline is just an externally defined linked list of vertices.)

bool TTdhOGR_target::WriteLinePts (OGRFeature *poFeature, TMultiLine *lineParam) {
  OGRLinearRing lineString;
  OGRPolygon currPoly;
  TVertex *currPt = lineParam->get_firstPt();
  while (currPt) {
    lineString.addPoint(currPt->getX(), currPt->getY());
    currPt = (TVertex*)currPt->next();
    }
  currPoly.addRing(&lineString);
  return (poFeature->SetGeometry(&currPoly) == OGRERR_NONE);
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timh