You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python从JSON坐标数据中识别Point/Polygon/MultiPolygon几何类型

Python实现几何类型自动识别方案

判定逻辑

三类目标几何类型的coordinates字段嵌套结构完全符合GeoJSON标准规范,可直接通过数组嵌套深度判定,无需额外地理空间计算:

  • Point:coordinates直接存储单个坐标对[x, y],数组嵌套深度为1(从coordinates层级开始计算,到数值元素为止)
  • Polygon:coordinates存储1个外环+0至多个内环(洞)的坐标集合,结构为[[[x,y], [x,y], ...], ...],数组嵌套深度为3
  • MultiPolygon:coordinates存储多个独立多边形的坐标集合,结构为[[[[x,y], ...], ...], ...],数组嵌套深度为4

你提供的示例数据coordinates为三层嵌套结构,判定为Polygon类型。

纯Python实现(无第三方依赖)

通过递归计算坐标数组的嵌套深度即可完成判定,代码如下:

import json

def calc_nest_depth(arr):
    # 递归计算数组嵌套深度,遇到非列表元素(即坐标数值)终止
    if not isinstance(arr, list):
        return 0
    return 1 + calc_nest_depth(arr[0]) if arr else 1

def get_geom_type(geojson_dict):
    coords = geojson_dict["geometry"]["coordinates"]
    depth = calc_nest_depth(coords)
    type_map = {
        1: "Point",
        3: "Polygon",
        4: "MultiPolygon"
    }
    if depth not in type_map:
        raise ValueError(f"非法坐标结构,嵌套深度为{depth},不属于Point/Polygon/MultiPolygon三类目标类型")
    return type_map[depth]

# 调用示例
if __name__ == "__main__":
    # 替换为你的JSON文件路径
    with open("geometry_data.json", "r", encoding="utf-8") as f:
        data = json.load(f)
    print(get_geom_type(data))

可选优化方案

如果后续需要做空间运算,可以直接安装shapely第三方库,加载几何对象后直接读取类型属性,代码更简洁,同时自动兼容格式不规范的坐标数据:

from shapely.geometry import shape
import json

with open("geometry_data.json", "r", encoding="utf-8") as f:
    data = json.load(f)
geom = shape(data["geometry"])
print(geom.geom_type) # 直接输出Point/Polygon/MultiPolygon

内容的提问来源于stack exchange,提问作者Self

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 22:18:23