我在不列颠群岛有geojson file个县,我正试图用一个合并的县代替伦敦的各个县,然后将结果保存为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中完成此任务吗?任何建议都将非常有帮助!
答案 0 :(得分:1)
以上所述有两个问题。第一个纯粹是一个疏忽:从d['features']
删除时,我需要以相反的顺序删除数组成员(删除索引0然后1不同于删除1然后0)。
从根本上说,上述geojson已经有损。坐标值的小数位数有限,无法将字节缩减为JSON文件大小。但这使合并的几何形状仅近似,并导致合并的多边形之间的缝隙很小:
因此,我得到的工作流程是获得高分辨率topojson file,将其转换为geojson,使用以下代码合并几何,然后限制十进制精度(如有必要)。 / p>
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)