7

Is there a way to programmatically generate buffer layers for vector layers using GDAL and python?

13

ogr has a buffer method. I am sitting behind a serious firewall, so I can't really dig around the internet too much, but here is a little snippet I found that should do the trick. I didn't test this, and will need some modification (i.e. set your driver type)- but it should get you going in the right direction.

#buffer.py
import sys,os
from osgeo import ogr

def buffer(infile,outfile,buffdist):
    try:
        ds=ogr.Open(infile)
        drv=ds.GetDriver()
        if os.path.exists(outfile):
            drv.DeleteDataSource(outfile)
        drv.CopyDataSource(ds,outfile)
        ds.Destroy()

        ds=ogr.Open(outfile,1)
        lyr=ds.GetLayer(0)
        for i in range(0,lyr.GetFeatureCount()):
            feat=lyr.GetFeature(i)
            lyr.DeleteFeature(i)
            geom=feat.GetGeometryRef()
            feat.SetGeometry(geom.Buffer(float(buffdist)))
            lyr.CreateFeature(feat)
        ds.Destroy()
    except:return False
    return True

if __name__=='__main__':
    usage='usage: buffer <infile> <outfile> <distance>'
    if len(sys.argv) == 4:
        if buffer(sys.argv[1],sys.argv[2],sys.argv[3]):
            print 'Buffer succeeded!'
            sys.exit(0)
        else:
            print 'Buffer failed!'
            sys.exit(1)
    else:
        print usage
        sys.exit(1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.