1

I am trying to extract 4 polygons (LA) from a country shapefile, combine them together as one. However, I ended up extracting those specific 4 polygons I was looking as a shapefile, but was unable to merge them together. Question now is: how do I merge these polygons together?

  import fiona
  from collections import OrderedDict

  SOURCE_FILE = "counties.shp"

  with fiona.open('counties.shp') as source:

  DESTINATION_FILE = "merged_polys.shp"
  SEARCH_STRING = "Dublin"
  SEARCH_PROPERTY = "nuts3name"
  geometries_to_merge = []

 with fiona.open(SOURCE_FILE) as source:

      total2011 = 0.0
      for feature in source:

           if feature['properties'][SEARCH_PROPERTY] == SEARCH_STRING:
              total2011 += feature['properties']['total2011']

            geometries_to_merge.append(shape(feature['geometry']))

            merged_polys = unary_union(geometries_to_merge)
            merged_polys_mapping = mapping(merged_polys)

            destination_feature = {}
            destination_feature["properties"] = OrderedDict()
            destination_feature["properties"]["total2011"] = total2011
            destination_meta = source.meta
            destination_feature['geometry'] = feature['geometry']
            destination_meta["schema"]["geometry"] = f"{merged_polys_mapping['type']}"
            destination_meta["schema"]["properties"] = OrderedDict()
            destination_meta["schema"]["properties"]["total2011"] = "float:33.15"

            with fiona.open(DESTINATION_FILE, "a", **destination_meta) as destination:
               destination.write(destination_feature)
6
  • Can you not do this in GIS? It is a trivial operation in a GIS.
    – Hornbydd
    Mar 28 '20 at 21:08
  • yes on arcmap, but this is for a programming excercise, so its needs to be done on pycharm. any ideas please
    – rachel
    Mar 28 '20 at 21:11
  • Why not look at the ArcMap help file at the Dissolve tool and at the bottom of every tool help page is how to call it in a scripting environment. You would need to pass in a feature layer with the appropriate polygons selected for the dissolve to to dissolve just those polygons into a single larger polygon. Your code above seems to be overkill.
    – Hornbydd
    Mar 28 '20 at 21:16
  • We dont have your data so we can't run your code to test it. The indenting and spacing looks ropey too - I don't think this code can possibly run as we see it. What happens when you run it? Error message? Bad output? Can you post working code and if possible point us to the data?
    – Spacedman
    Mar 28 '20 at 21:17
  • there are no error messages, it ran fine. but it extracted the 4 polygons i wanted but instead merging them together, it produced 4 separate polygons
    – rachel
    Mar 28 '20 at 21:21