Our current polygon only exists in memory. We can create a new shapefile and write the polygon geometry we created earlier to this shapefile. The script consists of the following steps:
- Import the modules and set the spatial reference (in this case, World Geodetic System 1984 (WGS1984)).
- Create the shapefile, then the layer using polygon geometry. Next, the geometry is put inside a feature and the feature in a layer. Notice that the script directly references the polygon from the earlier example.
- The catch is to use the right geometry type in the first line of code, which in this case should be wkbPolygon.
- The polygon geometry from our earlier example is referenced in this step and put into the shapefile.
- The shapefile is added as a layer in this step.
Take a look at the following code:
In: import osgeo.ogr, osgeo.osr
# 1 set the spatial reference
spatialReference = osgeo.osr.SpatialReference()
spatialReference.ImportFromProj4('+proj=longlat +ellps=WGS84
+datum=WGS84 +no_defs')
# 2 create a new shapefile
driver = osgeo.ogr.GetDriverByName('ESRI Shapefile')
shapeData = driver.CreateDataSource('my_polygon.shp')
# 3 create the layer
layer = shapeData.CreateLayer('polygon_layer', spatialReference,
osgeo.ogr.wkbPolygon)
layerDefinition = layer.GetLayerDefn()
# 4 geometry is put inside feature
featureIndex = 0
feature = osgeo.ogr.Feature(layerDefinition)
feature.SetGeometry(polygon)
feature.SetFID(featureIndex)
# 5 feature is put into layer
layer.CreateFeature(feature)
We can use ogrInfo to see if the file has been created correctly:
In: !ogrinfo my_polygon.shp
Out: INFO: Open of `my_polygon.shp'
using driver `ESRI Shapefile' successful.
1: my_polygon (Polygon)