문제

이 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

다른 팁

잘 ... 당신의 좌표로 파기 목록을 찍습니다 :

d['features'][0]['geometry']['coordinates'][0][0]
.

그래서이 작업을 수행 해야하는 것을 반전하려면 다음을 수행하십시오.

d['features'][0]['geometry']['coordinates'][0][0] = [i[::-1] for i in d['features'][0]['geometry']['coordinates'][0][0]]
.

또는 비트 클리너 IMO :

for l in d['features'][0]['geometry']['coordinates'][0][0]:
    l.reverse()
.

목록 이해를 사용하고 결과를 구조에 다시 할당합니다.

여기에 여러 목록이 있으므로 몇 가지 루프가 필요합니다.

for feature in response['features']:
    feature['geometry']['coordinates'] = [[
        [[long, lat] for lat, long in coords] for coords in poly]
        for poly in feature['geometry']['coordinates']]
.

이것은 'coordinates'의 구조가 안정적이라고 가정합니다.'type' 키가 있음을 알 수 있습니다. u'MultiPolygon 이외의 유형 이외의 유형이 사용되는 경우 구조를 변경하는 방법을 어떻게 변경해야 할 수 있습니다.

이것은 데이터를 다음과 같이 이동합니다.

>>> pprint.pprint(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.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'}
.

to :

>>> pprint.pprint(response)
{u'crs': {u'properties': {u'code': u'4326'}, u'type': u'EPSG'},
 u'features': [{u'geometry': {u'coordinates': [[[[-74.09688169446223,
                                                  39.81487959537135],
                                                 [-74.09587338924456,
                                                  39.81488113835475],
                                                 [-74.09614209870023,
                                                  39.8143317590967],
                                                 [-74.09633047532941,
                                                  39.8137616151959],
                                                 ....
                                                 [-74.0973277412355,
                                                  39.814255381955064],
                                                 [-74.09688169446223,
                                                  39.81487959537135]]]],
                              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"코드는 읽을 수 없으며 작동하지 않습니다.그것을 간단하고 어리 석다!

def swapCoords(x):
    out = []
    for iter in x:
        if isinstance(iter, list):
            out.append(swapCoords(iter))
        else:
            return [x[1], x[0]]
    return out



for feature in response['features']:
    feature['geometry']['coordinates'] = swapCoords(feature['geometry']['coordinates'])
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top