2

I created this script to merge all of the polygons in a shapefile into a single polygon. I am using Python 2.7.5, Shapely 1.3.0, and Fiona 1.1.5.

def merge(path_in, path_out):
    #Import Libraries
    import fiona
    from shapely.geometry import mapping, shape, MultiPolygon, Polygon
    from shapely.ops import cascaded_union
    from fiona import collection

    #Import shapefile
    with collection(path_in, "r") as input:
        input_driver = input.driver
        input_crs = input.crs
        input_schema = { 'geometry': 'Polygon', 'properties': { 'INT_DATE': 'int' } }

    #Open the file to be written
        with collection(path_out, "w", driver=input_driver, crs=input_crs, schema=input_schema) as output:
            shapes = []

            #Append all of the polygons to a list
            for f in input:
                shapes.append(shape(f['geometry']))

            #Merge all the polygons
            merged = MultiPolygon(cascaded_union(shapes))

            #Write the new shapefile
            output.write({'geometry': mapping(merged), 'properties':{'INT_DATE':'4'}})

if __name__ == "__main__":
    import sys
    merge(sys.argv[1],sys.argv[2])

When I run this program it returns no error message and outputs a shapefile with the attribute table I expect. However, the polygon is not there. Does anyone have any idea what is causing this? I have relied heavily on the Fiona users manual and "GIS with Python, Shapely, and Fiona" by Tom MacWright.

Is there a better way to use Shapely than using Fiona?

  • 1
    The script works for me, and I see a single merged polygon. You may need to post your shapefile as well. – Mike T Sep 11 '14 at 4:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.