gpt4 book ai didi

在 GeoJSON 响应中反转经度、纬度坐标的 Pythonic 方法

转载 作者:行者123 更新时间:2023-11-28 21:20:13 26 4
gpt4 key购买 nike

我想将此 JSON 响应中的坐标顺序从 (lat,lon) 反转为 (lon,lat):

url='https://www.sciencebase.gov/catalogMaps/mapping/ows/5342c5fce4b0aa151574a8ed?\
service=wfs&version=1.1.0&request=GetFeature&typeNames=sb:Conservation_Zone_WGS84&outputFormat=application/json'
response = requests.get(url).json()
print response

{u'crs': {u'properties': {u'code': u'4326'}, u'type': u'EPSG'},
u'features': [{u'geometry': {u'coordinates': [[[[39.81487959537135,
-74.09688169446223],
[39.81488113835475, -74.09587338924456],
[39.8143317590967, -74.09614209870023],
[39.8137616151959, -74.09633047532941],
[39.812950626580545, -74.09670529470912],
[39.8120075697193, -74.09698124228382],
[39.814255381955064, -74.0973277412355],
[39.81487959537135, -74.09688169446223]]]],
u'type': u'MultiPolygon'},
u'geometry_name': u'the_geom',
u'id': u'Conservation_Zone_WGS84.1',
u'properties': {u'ID': 1,
u'NAME': u'Sedge Island Marine Conservation Zone',
u'OBJECTID': 1,
u'SHAPE_AREA': 70259289.0821,
u'SHAPE_LEN': 40592.8006466,
u'WEB_LINK': u'http://www.state.nj.us/dep/fgw/sedge.htm'},
u'type': u'Feature'}],
u'type': u'FeatureCollection'}

我可以将其拆开,用蛮力将其重新粘在一起,但我想知道:在保持结构完好无损的同时更改顺序的 Pythonic 方法是什么?

最佳答案

使用 numpy 的解决方案应该适用于任何 geojson。它将翻转所有“坐标”。

import json
import requests
import numpy as np


def flip_geojson_coordinates(geo):
if isinstance(geo, dict):
for k, v in geo.iteritems():
if k == "coordinates":
z = np.asarray(geo[k])
f = z.flatten()
geo[k] = np.dstack((f[1::2], f[::2])).reshape(z.shape).tolist()
else:
flip_geojson_coordinates(v)
elif isinstance(geo, list):
for k in geo:
flip_geojson_coordinates(k)

url = "https://www.sciencebase.gov/catalogMaps/mapping/ows/5342c5fce4b0aa151574a8ed?\
service=wfs&version=1.1.0&request=GetFeature&typeNames=sb:Conservation_Zone_WGS84&outputFormat=application/json"
resp = requests.get(url)
gj = json.loads(resp.text)

print gj
flip_geojson_coordinates(gj)
print gj

关于在 GeoJSON 响应中反转经度、纬度坐标的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23019143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com