如何在现有shapefile中添加新功能

时间:2019-12-10 19:20:41

标签: python polygon shapefile

我是shapefile的新手,我尝试在现有shapefile中添加新的几何形状,该形状是我使用四个坐标的列表并使用此代码创建的

import ogr

def create_polygon(coords):          
    ring = ogr.Geometry(ogr.wkbLinearRing)
    for coord in coords:
        ring.AddPoint(coord[0], coord[1])

    # Create polygon
    poly = ogr.Geometry(ogr.wkbPolygon)
    poly.AddGeometry(ring)
    return poly.ExportToWkt()

def write_shapefile(poly, out_shp):   
    driver = ogr.GetDriverByName('Esri Shapefile')
    ds = driver.CreateDataSource(out_shp)
    layer = ds.CreateLayer('', None, ogr.wkbPolygon)
    # Add one attribute
    layer.CreateField(ogr.FieldDefn('id', ogr.OFTInteger))
    defn = layer.GetLayerDefn()

    # Create a new feature (attribute and geometry)
    feat = ogr.Feature(defn)
    feat.SetField('id', 1)

    # Make a geometry, from Shapely object
    geom = ogr.CreateGeometryFromWkt(poly)
    feat.SetGeometry(geom)

    layer.CreateFeature(feat)
    feat = geom = None  # destroy these

    # Save and close everything
    ds = layer = feat = geom = None

def main(coords, out_shp):
    poly = create_polygon(coords)
    write_shapefile(poly, out_shp)

if __name__ == "__main__":

    coords = [(0.22490093, 49.47406787),
        (0.22490440, 49.474067667),
        (0.22490496,49.47405773),
        (0.22490166,49.47405766),
        (0.22490093, 49.47406787)]

out_shp = r'D:\test.shp'
main(coords, out_shp)

接下来,我要做的是向此shapefile添加另一个功能,即第二个多边形,但是当我签入QGis时它什么也没有添加。为了尝试添加此形状,我用open代替了创建数据源:

    ds = driver.Open(out_shp,0)
    layer = ds.GetLayer()  

并将新坐标放入参数中。

如果有人有想法或可以告诉我我错过或误解了流程的哪一部分,或将我引导至类似的已解决帖子,那将是很好的! 非常感谢

0 个答案:

没有答案