我想从 OSM Overpass API 下载一些数据,并使用 Python 将这些数据转换为 geojson。 我准备了一个带有多边形的示例。我的用例有更大的文件。
下载部分正在工作,但在转换中我看到下面的错误。 但在前端我看到了这个多边形,并且我在 geojson 中也需要它。 最好
Failed to create multipolygon. Base shape with role "outer" is invalid. Group ids: [431444168,
431444172,
431444165,
431444166,
431444160,
431444162,
431444176,
1175053062,
431444159,
431444167,
431444173,
431444164,
431444155,
431444158,
431444156,
431444169,
431444163,
431444175,
431444174]
Failed to convert computed shapes to multipolygon 6417656
Element not converted 6417656
import osm2geojson
import codecs
import os
import json
import requests
from pathlib import Path
myinput_path = r"C:\tmp_geo"
myinput_filename="IT2.json"
myoutput_filename=myinput_filename.replace(".json",".geojson")
os.makedirs(myinput_path, exist_ok=True)
myinput=os.path.join(myinput_path,myinput_filename)
myoutput=os.path.join(myinput_path,myoutput_filename)
def download_osm_data(query, filepath_osm):
useragent = 'YourAppName/ContactInfo'
headers = {'User-Agent': useragent, 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
data = {'data': query}
try:
response = requests.post('https://overpass-api.de/api/interpreter', headers=headers, data=data, verify=False)
response.raise_for_status()
with open(Path(filepath_osm), 'w', encoding='utf-8') as f:
f.write(response.text)
return True
except requests.RequestException as e:
raise RuntimeError(f"Download error: {e}")
query = f"""
[out:json][timeout:25];
(
relation["boundary"="protected_area"]["type"="multipolygon"](43.1851, 9.6689, 44.4386, 11.3216);
);
out geom;
"""
download_osm_data(query, myinput)
with codecs.open(myinput, 'r', encoding='utf-8') as data:
inputdata = data.read()
geojsondata=osm2geojson.json2geojson(inputdata, filter_used_refs=False, log_level='INFO')
with open(myoutput, 'w', encoding='utf-8') as f:
json.dump(geojsondata, f, ensure_ascii=False, indent=2)
Overpass 直接支持geojson:
[out:json][timeout:25];
(
relation["boundary"="protected_area"]["type"="multipolygon"](43.1851, 9.6689, 44.4386, 11.3216);
);
convert item ::=::,::geom=geom(),_osm_type=type();
out geom;