那么上面有两个问题。第一个是纯粹的疏忽:从中删除时 d['features'] ,我需要以相反的顺序删除数组成员(删除索引0然后1不同于删除1然后0)。
d['features']
更重要的是,上述geojson已经有损。坐标值具有有限的小数位,可以减少JSON文件大小的字节数。但这使得合并几何只是近似的,并且导致合并多边形之间的间隙很小:
所以我的工作流程是获得高分辨率 topojson文件 ,将其转换为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)
结果: