Skip to content

Instantly share code, notes, and snippets.

@jgphilpott
Last active June 14, 2020 00:18
Show Gist options
  • Save jgphilpott/f0ebc18d5b6284a3709801a6e6c1636c to your computer and use it in GitHub Desktop.
Save jgphilpott/f0ebc18d5b6284a3709801a6e6c1636c to your computer and use it in GitHub Desktop.
A Python function for merging GeoJSON polygons.
import json
def merge_polygons(polygon_one, polygon_two):
with open("data.json") as input:
data = json.load(input)
map_one = None
map_two = None
for item in data:
if item["properties"]["code"] == polygon_one:
map_one = item
if item["properties"]["code"] == polygon_two:
map_two = item
if map_one and map_two:
if map_two["geometry"]["type"] == "Polygon":
map_two["geometry"]["coordinates"] = [map_two["geometry"]["coordinates"]]
map_two["geometry"]["type"] = "MultiPolygon"
for coord in map_one["geometry"]["coordinates"]:
if map_one["geometry"]["type"] == "Polygon":
map_two["geometry"]["coordinates"].append([coord])
elif map_one["geometry"]["type"] == "MultiPolygon":
map_two["geometry"]["coordinates"].append(coord)
for item in data:
if item["properties"]["code"] == polygon_two:
item = map_two
if item["properties"]["code"] == polygon_one:
data.remove(item)
with open("data.json", "w") as output:
json.dump(data, output, indent=2, sort_keys=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment