GIS:在Python中合并多多边形

GIS:在Python中合并多多边形,python,json,gis,geojson,shapely,Python,Json,Gis,Geojson,Shapely,我有一个不列颠群岛的县,我试图用一个合并县替换伦敦的各个县,然后将结果保存为geojson。(可以识别伦敦县,因为其TYPE_2属性设置为London Borough) 我认为我可以通过以下方式执行此任务: from shapely.geometry import Polygon, MultiPolygon, asShape from shapely.ops import unary_union import json, geojson j = json.load(open('british-

我有一个不列颠群岛的县,我试图用一个合并县替换伦敦的各个县,然后将结果保存为geojson。(可以识别伦敦县,因为其
TYPE_2
属性设置为
London Borough

我认为我可以通过以下方式执行此任务:

from shapely.geometry import Polygon, MultiPolygon, asShape
from shapely.ops import unary_union
import json, geojson

j = json.load(open('british-isles.geojson'))

# find the london counties
indices = [idx for idx, i in enumerate(j['features']) if \
    i['properties']['TYPE_2'] == 'London Borough']

# transform each london county into a shapely polygon
polygons = [asShape(j['features'][i]['geometry']) for i in indices]

# get the metadata for the first county
properties = j['features'][indices[0]]['properties']
properties['NAME_2'] = 'London'

# get the union of the polygons
joined = unary_union(polygons)

# delete the merged counties
d = j
for i in indices:
  del d['features'][i]

# add the new polygon to the features
feature = geojson.Feature(geometry=joined, properties=properties)
d['features'].append(feature)

# save the geojson
with open('geojson-british-isles-merged-london.geojson', 'w') as out:
  json.dump(d, out)
然而,这并不能正确地合并伦敦县——它会导致一系列的多边形碎片,而伦敦县过去是这样的


其他人知道我如何用Python完成这项任务吗?任何建议都会很有帮助

以上有两个问题。第一个纯粹是疏忽:从
d['features']
中删除时,我需要按相反顺序删除数组成员(先删除索引0,然后删除1与先删除1,然后删除0不同)

更重要的是,上面的geojson已经有损。坐标值具有有限的小数位数,可以减少JSON文件大小的字节。但这使得合并几何体只是近似的,并且会在合并的多边形之间产生较小的间隙:

因此,我的工作流程是获得高分辨率,将其转换为geojson,使用下面的代码合并几何体,然后限制十进制精度(如果需要)

结果:

from shapely.geometry import Polygon, MultiPolygon, asShape
from shapely.ops import unary_union, cascaded_union
from geojson import Feature
import json

j = json.load(open('GBR_adm2.json'))

# find the london counties
indices = [idx for idx, i in enumerate(j['features']) if \
    'London Borough' in i['properties']['TYPE_2']]

# transform each london county into a shapely polygon
polygons = [asShape(j['features'][i]['geometry']) for i in indices]

# get the metadata for the first county
properties = j['features'][indices[0]]['properties']
properties['NAME_2'] = 'London'

# get the union of the polygons
joined = unary_union(polygons)

# delete the merged counties
d = j
for i in reversed(sorted(indices)):
  del d['features'][i]

# add the new polygon to the features
feature = Feature(geometry=joined, properties=properties)
d['features'].append(feature)

# save the geojson
with open('british-isles-merged-london.geojson', 'w') as out:
  json.dump(d, out)