python - 使用简单的python脚本从经纬度坐标获取海拔
问题描述
我有一个从这个问题中得到的 python 脚本,该脚本将从 USGS 高程点查询服务中提取。但是,它在看似随机的时间后和我的查询完成之前一直超时并把我踢出去。我需要另一种方法来提取给定纬度坐标的高程数据。
这是我当前的查询:
# ========= pull elev from usgs server ======
# USGS POINT QUERY SERVICE ==================
url = r'https://nationalmap.gov/epqs/pqs.php?'
# ===========================================
# coordinates with known elevation
lat = [48.633, 48.733, 45.1947, 45.1962]
lon = [-93.9667, -94.6167, -93.3257, -93.2755]
# create df
df = pd.DataFrame({
'lat': lat,
'lon': lon
})
def elevation_function(df, lat_column, long_column):
elevations = []
counter = 0
start = time.time()
for lat, lon in zip(df[lat_column], df[long_column]):
# define rest query params
params = {
'output': 'json',
'x': lon,
'y': lat,
'units': 'Meters'
}
# format query string and return query value
result = requests.get((url + urllib.parse.urlencode(params)))
elevations.append(result.json()['USGS_Elevation_Point_Query_Service']['Elevation_Query']['Elevation'])
counter += 1
print('Proportion of job complete: {}'.format(round(counter/df.shape[0],3)))
end = time.time()
print(str(round(end - start)) + " seconds into job\n")
df['elev'] = elevations
return elevations
start = time.time()
count = 0
for i in range(100):
count += 1
elevations = elevation_function(df, lat_column='lat', long_column='lon')
end = time.time()
print(str(round(end - start)))
解决方案
简化函数并添加错误处理:
elevation_function
需要编写才能使用pandas.DataFrame.apply
- 使用
apply
, withaxis=1
, 自动遍历每一行坐标
- 使用
新功能:
make_remote_request
将继续发出请求,直到获得response
.- 更改异常以适应服务器返回的异常(例如
except (OSError, urllib3.exceptions.ProtocolError) as error
) - 可选地,并在异常中
import time
添加time.sleep(5)
before ,以与远程服务器配合使用。continue
def make_remote_request(url: str, params: dict) -> json:
"""
Makes the remote request
Continues making attempts until it succeeds
"""
count = 1
while True:
try:
response = requests.get((url + urllib.parse.urlencode(params)))
except (OSError, urllib3.exceptions.ProtocolError) as error:
print('\n')
print('*' * 20, 'Error Occured', '*' * 20)
print(f'Number of tries: {count}')
print(f'URL: {url}')
print(error)
print('\n')
count += 1
continue
break
return response
def eleveation_function(x):
url = 'https://nationalmap.gov/epqs/pqs.php?'
params = {'x': x[1],
'y': x[0],
'units': 'Meters',
'output': 'json'}
result = make_remote_request(url, params)
return result.json()['USGS_Elevation_Point_Query_Service']['Elevation_Query']['Elevation']
实现功能
import requests
import urllib
import urllib3
import pandas as pd
# coordinates with known elevation
lat = [48.633, 48.733, 45.1947, 45.1962]
lon = [-93.9667, -94.6167, -93.3257, -93.2755]
# create df
df = pd.DataFrame({'lat': lat, 'lon': lon})
lat lon
48.6330 -93.9667
48.7330 -94.6167
45.1947 -93.3257
45.1962 -93.2755
# apply the function
df['elevations'] = df.apply(eleveation_function, axis=1)
lat lon elevations
48.6330 -93.9667 341.14
48.7330 -94.6167 328.80
45.1947 -93.3257 262.68
45.1962 -93.2755 272.64
推荐阅读
- regex - How to get the string which is starting after front slash in Perl regex?
- node.js - Redis stream call back not able to return value
- c++ - Is it possible to have create mock method for each argument from parameter pack?
- javascript - How to convert Vue 2 web site to PWA wab app?
- nginx - Nginx re-routing query
- php - PHP 不能只获得一个值
- powerbi - 计算 2 列中值的出现次数
- linux - Linux shell 选择目录和子目录中的文件
- eloquent - 如何通过 laravel 关系过滤
- django-rest-framework - 使用序列化器将 json/xml 转换为 json