Python中如何将重叠Polygon合并为带内环的GeoJSON FeatureCollection?
多边形重叠合并为带内环Polygon的实现方案
我有如下GeoJSON格式的FeatureCollection数据,包含三个Polygon要素,其中前两个Polygon存在重叠区域:
data_01 = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [[2, 2], [2, 22], [22, 22], [22, 2], [2, 2]] ] }, "properties": {"z": 1412.5, "la": "ba"} }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [[12, 16], [7, 10], [17, 10], [12, 16]] ] }, "properties": {"z": 1412.5, "la": "ba"} }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [[27, 15], [24, 12], [29, 12], [27, 15]] ] }, "properties": {"z": 1412.5, "la": "ba"} } ] }
需求是将重叠的前两个Polygon合并为一个带内环的Polygon,第三个不重叠的Polygon保持独立,最终得到如下结构的data_final:
data_final = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [[27, 15], [24, 12], [29, 12], [27, 15]] ] }, "properties": {"z": 1412.5, "la": "ba"} }, { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [[2, 2], [2, 22], [22, 22], [22, 2], [2, 2]], [[12, 16], [7, 10], [17, 10], [12, 16]] ] }, "properties": {"z": 1412.5, "la": "ba"} } ] }
目前已实现数据读取的代码:
import json with open("data_01.json", 'r', encoding='utf-8-sig') as fh: d = fh.read() f = json.loads(d) j = f['features'][0:] for i in j: poly_coord = i['geometry']['coordinates'][0:] poly_coord = poly_coord[0] print(poly_coord )
实现逻辑与完整代码
要完成这个需求,我们可以借助shapely库处理空间几何运算,具体步骤如下:
- 将GeoJSON中的Polygon转换为shapely几何对象,方便进行包含关系判断
- 针对前两个多边形的包含关系,构建带内环的Polygon
- 保留第三个独立多边形,整理为最终的FeatureCollection
完整代码如下:
import json from shapely.geometry import shape # 读取GeoJSON数据 with open("data_01.json", 'r', encoding='utf-8-sig') as fh: feature_collection = json.load(fh) features = feature_collection['features'] final_features = [] # 处理前两个重叠多边形 poly1_shape = shape(features[0]['geometry']) poly2_shape = shape(features[1]['geometry']) # 检查第二个多边形是否完全被第一个包含(根据你的数据场景) if poly1_shape.contains(poly2_shape): # 提取外环和内环坐标,构建带洞的Polygon outer_coords = list(poly1_shape.exterior.coords) inner_coords = list(poly2_shape.exterior.coords) combined_feature = { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [outer_coords, inner_coords] }, "properties": features[0]['properties'] } final_features.append(combined_feature) # 添加第三个独立多边形 final_features.append(features[2]) # 构建最终的FeatureCollection data_final = { "type": "FeatureCollection", "features": final_features } # 保存结果到文件(可选) with open("data_final.json", 'w', encoding='utf-8') as fh: json.dump(data_final, fh, indent=2) # 打印验证结果 print(json.dumps(data_final, indent=2))
代码说明
- 使用
shapely.geometry.shape将GeoJSON几何转为shapely对象,便于执行空间判断 - 针对你的数据场景,第二个多边形完全处于第一个内部,直接将其坐标作为内环添加到第一个多边形的坐标列表中,形成带洞的Polygon
- 如果后续遇到部分重叠的场景,可以扩展代码使用
shapely.ops.unary_union来合并多边形(比如生成MultiPolygon) - 最终结果可保存为新的GeoJSON文件,或直接用于后续处理
内容的提问来源于stack exchange,提问作者user20567574
相关产品推荐
相关产品推荐

