In case somebody needs to do the buffering of geometries (using pure OGR).

I am trying to create reduced/extended polygons from an existing polygon using OGR in Python.

The abstract idea that I have is to use the "Buffering" function of OGR to achieve the goal that is dressed here and here (using GIS interfaces).

More precisely I want to create a buffer with negative/positive distance and based on that create a new polygon with borders drawn inward/outward.

For this I used Create Buffer from GDAL/OGR cookbook as the template with a small addition of importing SRS from the input polygon to the output(buffer) polygon.

I have been suggested to use SQLite dialect in order to achieve it. This means that there are certainly more options to get the same results.

Here is the code:

import os
import sys
from osgeo import ogr 
from osgeo import osr

def createBuffer(inputfn, outputBufferfn, bufferDist):
    inputds = ogr.Open(inputfn)
    inputlyr = inputds.GetLayer()

    shpdriver = ogr.GetDriverByName('ESRI Shapefile')
    if os.path.exists(outputBufferfn):
    outputBufferds = shpdriver.CreateDataSource(outputBufferfn)
    # create the spatial reference system, WGS84
    #srs =  osr.SpatialReference()
    srs = inputlyr.GetSpatialRef()
    bufferlyr = outputBufferds.CreateLayer(outputBufferfn,srs, 
    featureDefn = bufferlyr.GetLayerDefn()

    for feature in inputlyr:
        ingeom = feature.GetGeometryRef()
        geomBuffer = ingeom.Buffer(bufferDist)

        outFeature = ogr.Feature(featureDefn)
        outFeature = None

def main(inputfn, outputBufferfn, bufferDist):
    createBuffer(inputfn, outputBufferfn, bufferDist)

if __name__ == "__main__":
    inputfn = 'polygon.shp'
    outputBufferfn = 'polygonBuffer.shp'
    bufferDist = -1.0

    main(inputfn, outputBufferfn, bufferDist)
  • 1
    please add your formatted code – Ian Turton Apr 15 at 10:41
  • 1
    Use ExecuteSQL with the SQLite dialect and the SpatiaLite function ST_Buffer. – user30184 Apr 15 at 11:35
  • 1
    Please don't add an Answer inside your Question. The idea behind including code is to show where you got stuck, so the folks who could help don't need to write a ton of code which might not even fit in the context of your Question. If you go ahead and solve it after the Question is closed, then you ought to either edit the question enough to get it reopened (then write a full Answer) or contact a moderator (via Flag) to request reopening outside the queue (and then write a full Answer). – Vince Apr 16 at 13:02

Your Answer

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

Browse other questions tagged or ask your own question.