将 .geojson 转换为 .wkt | 提取“坐标”

Dan*_*l99 1 python json geojson python-3.x

目标:最终,转换.geojson.wkt. 在这里,我想提取所有coordinates,每个作为一个列表。

my.geojson中,有n个:{"type":"Polygon","coordinates":...

更新:我已经成功提取了第一个coordinates. 但是,该文件有两个coordinates.


每个.geojson至少有 1 个coordinates,但可能有更多。

如何动态提取许多的所有键值coordinates

代码:

from pathlib import Path
import os
import geojson
import json
from shapely.geometry import shape


ROOT = Path('path/')

all_files = os.listdir(ROOT)
geojson_files = list(filter(lambda f: f.endswith('.geojson'), all_files))

for gjf in geojson_files:
    with open(f'{str(ROOT)}/{gjf}') as f:
        gj = geojson.load(f)
    o = dict(coordinates = gj['features'][0]['geometry']['coordinates'], type = "Polygon")
    geom = shape(o)
    wkt = geom.wkt
Run Code Online (Sandbox Code Playgroud)

所需输出:.wktgeojson 中所有坐标均为1

Jas*_*nM1 5

要将 GeoJSON 文件中的一系列几何图形转换为 WKT,shape() 函数可以将 GeoJSON 几何图形转换为形状对象,然后将其格式化为 WKT 和/或投影到不同的坐标参考系。

如果要在多边形位于形状对象中后访问其坐标,请使用
x,y = geo.exterior.xy.

如果只想将一系列 GeoJSON 文件转换为每个 GeoJSON 文件一个 .wkt 文件,请尝试以下操作:

from pathlib import Path
import json
from shapely.geometry import shape

ROOT = Path('path')

for f in ROOT.glob('*.geojson'):
    with open(f) as fin, open(f.with_suffix(".wkt"), "w") as fout:
        features = json.load(fin)["features"]
        for feature in features:
            geo = shape(feature["geometry"])
            # format geometry coordinates as WKT
            wkt = geo.wkt
            print(wkt)
            fout.write(wkt + "\n")
Run Code Online (Sandbox Code Playgroud)

此输出使用您的示例 my.geojson 文件。

输出:

POLYGON ((19372 2373, 19322 2423, ...
POLYGON ((28108 25855, 27755 26057, ...
Run Code Online (Sandbox Code Playgroud)

如果需要将坐标转换为 EPSG:4327 (WGS-84)(例如 23.314208、37.768469),可以使用pyproj

将 GeoJSON 文件集合转换为 WGS-84 中新的 GeoJSON 文件的完整代码。

POLYGON ((19372 2373, 19322 2423, ...
POLYGON ((28108 25855, 27755 26057, ...
Run Code Online (Sandbox Code Playgroud)

假设转换是从 EPSG:3857 到 EPSG:4327 并且中心点位于 lon=23, lat=37,输出 GeoJSON 文件将如下所示:

{"features": [{"type": "Polygon", "geometry": {"coordinates": [[[23.897879, 38.012554], ...
Run Code Online (Sandbox Code Playgroud)