[gdal-dev] Python bindings: How to merge two geometries

Frank Warmerdam warmerdam at pobox.com
Wed Sep 7 13:07:24 EDT 2011


On Wed, Sep 7, 2011 at 9:59 AM, vasile <vasile.cotovanu at webgis.ro> wrote:
> Hello all,
>
> I have a Shapefile layer and try to merge some features from it using OGR
> Python bindings. Basically there are simple polylines that are connected
> each-other, so the result should be a simple polyline as well (and not a
> collection)
>
> I am using this snippet of code(warning: that's my beginner's Python code)
> to accomplish the merge but I get a 'Segmentation Fault 11' error:
> http://pastie.org/2498129
...

Vasile,

The problem, I believe, relates to object lifetimes with the Python
OGR bindings.  In particular GetGeometryRef() returns a reference
to the geometry owned by the feature which is destored when
the feature falls out of scope even if it is still referenced in Python.

The fix then is to clone it when you want it to live for a while.
Also, I believe that the Union method returns the unioned
geometry - it does not modify the geometry on which it is invoked.
Lastly, please try to avoid assuming feature id's are consecutive.
So an improved script might look a bit like:

  newGeometry = None
  for feature in Layer:
      geometry = feature.GetGeometryRef()
      if newGeometry is None:
        newGeometry = geometry.Clone()
      else:
        newGeometry = newGeometry.Union(geometry)

  print newGeometry

I am thinking we ought to include a GetGeometry() method on
ogr.Feature that returns a clone immediately, and promote it
as the primary method to use to get geometries in Python.
GetGeometryRef() could be kept around for compatability
and for optimizing performance in cases where care is taken
about lifetimes.

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 Software Developer


More information about the gdal-dev mailing list