调用Geo Admin API获取GeoJSON中LineString高程时geom参数错误
解决Swiss Geo Admin Profile API的geom参数错误问题
问题概述
我尝试根据Swiss Geo Admin的Profile API文档,从GeoJSON文件中提取LineString的高程信息,请求地址为https://api3.geo.admin.ch/rest/services/profile.csv,但始终收到错误:传入的'geom'参数不是GeoJSON类型。
我的GeoJSON文件内容:
{ "type": "FeatureCollection", "name": "test", "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } }, "features": [ { "type": "Feature", "properties": { "Name": null, "description": "", "altitudeMode": "clampToGround", "tessellate": 1, "type": "linepolygon" }, "geometry": { "type": "LineString", "coordinates": [ [ 7.349510580151255, 45.998132989830559 ], [ 7.346422156898689, 46.039529058312063 ], [ 7.287112064012824, 46.093617348068292 ], [ 7.236173542687846, 46.127135334945002 ] ] } } ] }
我的Python代码:
import requests import json api_url = "https://api3.geo.admin.ch/rest/services/profile.csv" file_path = "geojson.GEOJSON" with open(file_path) as f: geojson = json.load(f) r = requests.get(api_url, params=dict(geom=geojson)) print(r.json())
执行后错误输出:
{'error': {'code': 400, 'message': 'Invalid geom parameter, must be a GEOJSON'}, 'success': False}
错误原因
- 参数类型不匹配:直接将Python字典(解析后的GeoJSON对象)传入
geom参数,API要求的是序列化后的JSON字符串,而非Python原生对象。 - GeoJSON结构不符合要求:API需要
geom参数为单个几何对象(如LineString),但传入的是FeatureCollection,必须提取其中的LineString几何部分。 - 坐标系不兼容:GeoJSON使用的是CRS84(WGS84经纬度),而Swiss Geo Admin API默认使用瑞士本地坐标系(LV95,EPSG:2056),不转换会导致API无法识别位置,甚至返回无效数据。
修正后的代码
import requests import json from pyproj import Transformer api_url = "https://api3.geo.admin.ch/rest/services/profile.csv" file_path = "geojson.GEOJSON" # 读取并解析GeoJSON文件 with open(file_path) as f: geojson_data = json.load(f) # 提取Feature中的LineString几何对象 line_geometry = geojson_data["features"][0]["geometry"] # 将WGS84经纬度转换为LV95坐标系(EPSG:2056) transformer = Transformer.from_crs("EPSG:4326", "EPSG:2056", always_xy=True) converted_coords = [ transformer.transform(lon, lat) for lon, lat in line_geometry["coordinates"] ] line_geometry["coordinates"] = converted_coords # 将几何对象序列化为JSON字符串 geom_json = json.dumps(line_geometry) # 构造请求参数并发送请求 params = { "geom": geom_json, "sr": 2056 # 指定输出坐标系为LV95 } r = requests.get(api_url, params=params) # 输出CSV格式的高程数据 print(r.text)
关键说明
- 提取几何对象:确保
geom参数是单个LineString(或Point/MultiLineString),而非FeatureCollection或Feature结构。 - 序列化JSON:通过
json.dumps()将Python对象转为标准JSON字符串,满足API的参数格式要求。 - 坐标系转换:瑞士地理数据基于LV95/LV03坐标系,必须将WGS84坐标转换为对应坐标系,否则API无法定位。
pyproj库用于完成转换,需提前安装:pip install pyproj。 - 响应格式切换:若需要JSON格式的响应,可将请求地址改为
profile.json。
内容的提问来源于stack exchange,提问作者user20166765
相关产品推荐
相关产品推荐

