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

如何在空JSON中嵌套对象生成GeoJSON?Python坐标嵌套实现

解决GeoJSON坐标双层嵌套问题(适配geojson.io规范)

核心思路

Python中实现嵌套对象本质就是列表嵌套列表,GeoJSON的坐标双层结构对应二维列表,直接通过方括号包裹即可生成。关键是先明确你要生成的GeoJSON要素类型对应的坐标规范:

  • LineString/MultiPoint:坐标为双层列表 [[lon1, lat1], [lon2, lat2], ...]
  • Point:单层列表 [lon, lat](若需强制双层,可改为[[lon, lat]]对应MultiPoint类型)
  • Polygon:三层列表(外层包裹线性环)[[[lon1, lat1], ..., [lon1, lat1]]]

基于Pandas的实现示例

场景1:生成LineString要素(双层坐标)

假设你的DataFrame按feature_id分组,每组包含多个坐标点:

import pandas as pd
import json

# 示例DataFrame
df = pd.DataFrame({
    "feature_id": [1, 1, 2, 2],
    "lon": [116.4, 116.41, 116.5, 116.51],
    "lat": [39.9, 39.91, 39.8, 39.81],
    "name": ["路线A", "路线A", "路线B", "路线B"]
})

# 初始化GeoJSON结构
geojson = {
    "type": "FeatureCollection",
    "features": []
}

# 按要素分组生成坐标
for feature_id, group in df.groupby("feature_id"):
    # 生成双层坐标列表:每个坐标对是子列表,整体为大列表
    coords = group.apply(lambda row: [row["lon"], row["lat"]], axis=1).tolist()
    # 构造Feature
    feature = {
        "type": "Feature",
        "properties": {
            "id": feature_id,
            "name": group["name"].iloc[0]
        },
        "geometry": {
            "type": "LineString",
            "coordinates": coords  # 直接使用双层列表
        }
    }
    geojson["features"].append(feature)

# 保存为GeoJSON文件
with open("lines.geojson", "w", encoding="utf-8") as f:
    json.dump(geojson, f, ensure_ascii=False, indent=2)

场景2:生成MultiPoint要素(双层坐标)

若你需要将单个点包装成双层结构(适配特定需求):

import pandas as pd
import json

df = pd.DataFrame({
    "name": ["点位1", "点位2"],
    "lon": [116.4, 116.5],
    "lat": [39.9, 39.8]
})

geojson = {"type": "FeatureCollection", "features": []}

for idx, row in df.iterrows():
    # 双层括号:把单个坐标对再包一层列表
    coords = [[row["lon"], row["lat"]]]
    feature = {
        "type": "Feature",
        "properties": {"name": row["name"]},
        "geometry": {
            "type": "MultiPoint",
            "coordinates": coords
        }
    }
    geojson["features"].append(feature)

with open("multipoints.geojson", "w", encoding="utf-8") as f:
    json.dump(geojson, f, ensure_ascii=False, indent=2)

简化工具:使用geojson库

如果不想手动构造字典,可借助官方geojson库自动生成符合规范的结构:

from geojson import Feature, FeatureCollection, LineString
import pandas as pd

df = pd.DataFrame({
    "feature_id": [1, 1],
    "lon": [116.4, 116.41],
    "lat": [39.9, 39.91]
})

grouped = df.groupby("feature_id")
features = []
for feature_id, group in grouped:
    coords = list(zip(group["lon"], group["lat"]))
    line = LineString(coords)  # 自动生成双层坐标结构
    feature = Feature(geometry=line, properties={"id": feature_id})
    features.append(feature)

feature_collection = FeatureCollection(features)

# 保存
with open("output.geojson", "w") as f:
    f.write(feature_collection.dumps(ensure_ascii=False, indent=2))

验证规范

生成文件后可直接拖入geojson.io,若能正常显示和编辑,说明结构符合要求。重点注意:

  • 坐标顺序必须是**[经度, 纬度]**(GeoJSON规范要求)
  • Polygon类型需要闭合(首尾坐标一致)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:01:33