使用简单的python脚本从纬度经度坐标获取高程 [英] Obtain elevation from latitude longitude coordinates with a simple python script

查看:21
本文介绍了使用简单的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
")
    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
    • applyaxis=1配合使用,可自动迭代每一行坐标

新增功能:

  • make_remote_request将继续发出请求,直到response
  • 更改异常以适应服务器返回的异常(例如except (OSError, urllib3.exceptions.ProtocolError) as error)
  • 可以选择import time,并在异常中的continue之前添加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('
')
            print('*' * 20, 'Error Occured', '*' * 20)
            print(f'Number of tries: {count}')
            print(f'URL: {url}')
            print(error)
            print('
')
            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

这篇关于使用简单的python脚本从纬度经度坐标获取高程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆