I want to read all the points in a polygon shapefile and use their coordinates to make a new point shapefile, then find the min and max of the X coordinates. So here is the code I wrote for the first part (polygon to point) and it makes the point shapefile but the attribute table is just has the ID field.
from osgeo import gdal from osgeo import ogr from osgeo import gdal_array from osgeo import gdalconst from osgeo.gdalconst import * import os os.chdir('C:\Fcounty') driver = ogr.GetDriverByName("ESRI Shapefile") fname = 'PolygonFC.shp' vector = driver.Open(fname, 0) layer = vector.GetLayer(0) ofname = 'PointFC.shp' if os.path.exists(ofname): driver.DeleteDataSource(ofname) ovector = driver.CreateDataSource(ofname) olayer = ovector.CreateLayer('points', geom_type=ogr.wkbPoint) fieldDefn = ogr.FieldDefn('id', ogr.OFTInteger) olayer.CreateField(fieldDefn) featureDefn = olayer.GetLayerDefn() point = ogr.Geometry(ogr.wkbPoint) k = 0 f = layer.GetNextFeature() while f: geom = f.GetGeometryRef() ring = geom.GetGeometryRef(0) np = ring.GetPointCount() for j in range(np): p = ring.GetPoint(j) ofeature = ogr.Feature(featureDefn) point.AddPoint(p, p) ofeature.SetGeometry(point) ofeature.SetField('id', k) olayer.CreateFeature(ofeature) ofeature.Destroy() k += 1 f.Destroy() f = layer.GetNextFeature() vector.Destroy() ovector.Destroy()
As I mentioned this part is not giving me any error (I know it does not mean it works). So my questions are:
- Is this the right code? why there is no other fields beside 'ID' in attribute table?
- How can I do the second part of it? (the coordinates for lowest and highest X) I want to get it from the point shapefile, not the polygon.