首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将GeoJSON FeatureCollection转换为GeoJSON几何对象

将GeoJSON FeatureCollection转换为GeoJSON几何对象
EN

Stack Overflow用户
提问于 2015-03-21 00:23:45
回答 2查看 1.3K关注 0票数 0

我目前有一个GeoJSON FeatureCollection,但是我需要在Python语言中对这个文件执行的函数只支持GeoJSON几何对象,如PointPolygon (没有所有的属性和坐标数据)。有没有一种方法可以在Python语言中简单地将GeoJSON FeatureCollection转换为GeoJSON几何对象?

EN

回答 2

Stack Overflow用户

发布于 2016-03-11 18:41:40

嗯,最简单的方法是循环遍历您的特征集合,并从中提取几何图形。我想你现在已经找到了你问题的答案,因为从那以后就没有另一个帖子了?

票数 0
EN

Stack Overflow用户

发布于 2021-07-25 03:40:12

要拆分GeoJSON特性集合的特性,需要遍历feature元素并导出每个特性。

代码语言:javascript
运行
复制
for f in data['features']:
    if f.get("type") == "Feature":
        with open(somefile, "w") as out:
            json.dump(f, out)

以下Python代码将遍历GeoJSON特性集合并拆分每个特性,将其保存在单独的GeoJSON文件中。

如果源GeoJSON文件有10个要素,则它们将保存在文件中: 1.geojson,2.geojson,...,10.geojson。

代码语言:javascript
运行
复制
import json
import sys

class Splitter:
    def __init__(self):
        self.count = 0

    def check(self, input_file):
        print("Input:", input_file)
        with open(input_file, encoding="utf-8") as file:
            data = json.load(file)
        data_type = data.get("type")
        if data_type == "FeatureCollection":
            for f in data['features']:
                obj_type = f.get("type")
                if obj_type == "Feature":
                    self.export_feature(data, f)
                else:
                    print("WARN: non-feature:", obj_type)
        elif data_type == "Feature":
            print("GeoJSON is already a feature object")
        else:
            print("WARN: unknown/other type:", data_type)

    def export_feature(self, parent, feature):
        self.count += 1
        name = f"{self.count}.geojson"
        print("Output:", name)
        if "crs" in parent and "crs" not in feature:
            # copy coordinate reference system (CRS) definition from parent
            # if not present in feature
            feature["crs"] = parent["crs"]
        with open(name, "w") as out:
            json.dump(feature, out)

##############################################################################
# main #
##############################################################################

if len(sys.argv) < 2:
    print("usage: geojson-split.py <file>")
    sys.exit(0)

splitter = Splitter()
for f in sys.argv[1:]:
    splitter.check(f)

如果需要将GeometryCollection拆分为其组件几何图形,请参阅相关answer

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29171316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档