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