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:and then for each line you need to create:
However this would be a minor gain. You could become more expressive and concise in this way:
where
coords
is a list of tuples:and it can even be longer than 2:
and you would use it just like this:
Incidentally, this follows quite closely the GeoJSON specification for LINESTRING geometries.