如何使用open-elevation获取多地点海拔?算法课图论项目需该数据
使用open-elevation获取多地点海拔数据的实操指南
我之前做图论相关的项目时,刚好也遇到过类似的海拔数据获取问题,open-elevation确实是个靠谱的解决方案,给你拆解下具体怎么用,适配你多地点的需求:
1. 单地点基础请求(快速测试)
如果只是想先验证效果,可以用简单的GET请求获取单个坐标的海拔:
- 用
curl命令直接测试:
返回的JSON响应里,curl https://api.open-elevation.com/api/v1/lookup?locations=39.7392,-104.9903elevation字段就是对应的海拔数值(单位:米)。 - Python代码示例:
import requests def get_single_elevation(lat, lon): url = f"https://api.open-elevation.com/api/v1/lookup?locations={lat},{lon}" response = requests.get(url).json() return response['results'][0]['elevation'] # 调用示例:获取丹佛的海拔 elevation = get_single_elevation(39.7392, -104.9903) print(f"目标地点海拔:{elevation} 米")
2. 批量处理多地点(核心需求适配)
因为你需要处理一组目标地点,批量请求能大幅提升效率,open-elevation支持一次性提交多个坐标,用竖线|分隔即可:
- 批量
curl请求示例:curl https://api.open-elevation.com/api/v1/lookup?locations=39.7392,-104.9903|37.7749,-122.4194|40.7128,-74.0060 - Python批量请求代码(推荐,方便后续和你的路径算法整合):
import requests def get_batch_elevations(coordinate_list): # coordinate_list格式:[(纬度1, 经度1), (纬度2, 经度2), ...] location_str = "|".join([f"{lat},{lon}" for lat, lon in coordinate_list]) url = f"https://api.open-elevation.com/api/v1/lookup?locations={location_str}" response = requests.get(url).json() # 把返回结果和原坐标一一对应,避免顺序混乱 result_list = [] for idx, res in enumerate(response['results']): result_list.append({ 'latitude': coordinate_list[idx][0], 'longitude': coordinate_list[idx][1], 'elevation': res['elevation'] }) return result_list # 调用示例:批量获取三个城市的海拔 target_coords = [(39.7392, -104.9903), (37.7749, -122.4194), (40.7128, -74.0060)] elevation_results = get_batch_elevations(target_coords) for item in elevation_results: print(f"坐标({item['latitude']}, {item['longitude']})的海拔:{item['elevation']} 米")
3. 结合你的最短路径项目的实用技巧
- 如果你是从OpenStreetMap提取的路径节点,直接把这些节点的
lat和lon字段整理成上述的坐标列表,就能批量获取所有节点的海拔,不用逐个处理。 - 极少数偏远地区可能返回
elevation为None,可以提前设置默认值(比如用周边节点的海拔插值填充),避免影响后续的路径计算。 - 公开API没有严格的限流,但单次批量请求的坐标数量建议控制在1000以内,避免请求超时或被临时拦截。
4. 进阶:本地部署open-elevation服务(应对超大量数据)
如果你的项目需要处理上万级别的节点,公开API的效率可能不够,这时可以考虑自己部署open-elevation的开源服务:
- 它基于SRTM全球高程数据,你可以下载对应区域的高程数据集,然后在本地搭建API服务,完全不受外部请求限制,处理速度也更快。
内容的提问来源于stack exchange,提问作者mrzephyr




