用一个简单的python脚本从经纬度坐标获得高程

2024-05-29 00:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我从这个question得到了一个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)))

Tags: dftimecountercolumnparamsquerystartlong
1条回答
网友
1楼 · 发布于 2024-05-29 00:17:04

简化功能并添加错误处理:

  • elevation_function需要编写才能使用{a1}
    • 使用apply,与axis=1,自动迭代每一行坐标

新功能:

  • make_remote_request将继续发出请求,直到它得到response。在
  • 更改异常以适应服务器返回的异常(例如except (OSError, urllib3.exceptions.ProtocolError) as error
  • 可选地,import time并在异常中的time.sleep(5)之前添加time.sleep(5),以便更好地处理远程服务器。在
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']

实现功能

^{pr2}$

相关问题 更多 >

    热门问题