Writing polygon data to a newly created shapefile

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:

  1. Import the modules and set the spatial reference (in this case, World Geodetic System 1984 (WGS1984)).
  2. 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.
  3. The catch is to use the right geometry type in the first line of code, which in this case should be wkbPolygon.
  4. The polygon geometry from our earlier example is referenced in this step and put into the shapefile.
  5. 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)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset