[GIS] How to create a shapefile consisting of 2 lines using Python OGR

ogrpolyline-creationpython

How would you create a shapefile consisting of 2 lines using Python OGR?

First line is no problem, but how do you reuse MyLine and Feature objects to create the second line?

Ultimately this will be in a loop with thousands of lines created…

from osgeo import ogr
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.CreateDataSource('c:/temp/testlines.shp')
layer = datasource.CreateLayer('layerName',geom_type=ogr.wkbLineString)

#create first line 0,0 to 10,0:
myLine = ogr.Geometry(type=ogr.wkbLineString)
myLine.AddPoint_2D(0,0)
myLine.AddPoint_2D(10,0)
feature.SetGeometryDirectly(myLine)
layer.CreateFeature(feature)

#create next line 0,0 to 0,10?:
#how to you reuse the myLine, feature objects?
#myLine.DeletePoints()#something like this?
myLine.AddPoint_2D(0,0)
myLine.AddPoint_2D(0,10)
#feature.NesGeometry() #something lik this?
feature.SetGeometry(myLine)
layer.CreateFeature(feature)

Best Answer

You could make myLine into a factory function:

def myLine():
    return ogr.Geometry(type=ogr.wkbLineString)

and then for each line you need to create:

line = myLine()
line.AddPoint_2D(0,0)
line.AddPoint_2D(0,10)
feature.SetGeometryDirectly(line)

However this would be a minor gain. You could become more expressive and concise in this way:

def myLine(coords):
    line = ogr.Geometry(type=ogr.wkbLineString)
    for xy in coords:
        line.AddPoint_2D(xy[0],xy[1])
    return line

where coords is a list of tuples:

coords = [(0,0), (0,10)]

and it can even be longer than 2:

coords = [(0,0), (0,10), (10,0)]

and you would use it just like this:

line = myLine([(0,0), (0,10)])
feature.SetGeometryDirectly(line)

Incidentally, this follows quite closely the GeoJSON specification for LINESTRING geometries.