[GIS] Making buffer from line using GDAL and Python

buffergdalpython

I am trying to make a buffer from a line using gdal.

I use the example in the gdal Cookbook

import ogr, os

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

    shpdriver = ogr.GetDriverByName('ESRI Shapefile')
    if os.path.exists(outputBufferfn):
        shpdriver.DeleteDataSource(outputBufferfn)
    outputBufferds = shpdriver.CreateDataSource(outputBufferfn)
    bufferlyr = outputBufferds.CreateLayer(outputBufferfn, geom_type=ogr.wkbPolygon)
    featureDefn = bufferlyr.GetLayerDefn()

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

        outFeature = ogr.Feature(featureDefn)
        outFeature.SetGeometry(geomBuffer)
        bufferlyr.CreateFeature(outFeature)

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


    if __name__ == "__main__":
        inputfn = 'obli.shp'
        outputBufferfn = 'oblibuffer001.shp'
        bufferDist = 0.01

        main(inputfn, outputBufferfn, bufferDist)

 # creating the projection file. Not included in the cookbook
    prj = open('oblibuffer001.prj', 'w')
    proyeccion = 'GEOGCS["GCS_WGS_1984",
    DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],' \
             'PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]'
    prj.write(proyeccion)
    prj.close()

It works fine

http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html?highlight=buffer

But I can not understand exactly what kind of units I must use in the bufferDist

Ussing 0.01 I think it was a kilometre but the result is different depending the direction of the line. For example
Using a parallel_direction_line using bufferDist = 0.01 meassured in the map the buffer is 1,1 km
a meridiam_direction_line using bufferDist = 0.01 meassured in the map the buffer is 0.456 km

but a oblicual_direction_line using bufferDist = 0.01 meassured in the map the buffer is 0,57 km

How can I find the value for the bufferDist variable I think depends on the latitude and the direction of the line?

Best Answer

Your buffer distance is given in the units of your dataset. Your coordinate system is lon/lat geographic. Thus 0.01 = 0.01 decimal degrees. To be able to buffer by 1 km (1000 m) you need to reproject your dataset to a projected coordinate system which has units in metres.

There are examples in the Python GDAL/OGR Cookbook of how to reproject layers and geometries.