Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 12 down vote accepted

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)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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