Python: 从经纬度值获取海拔

Python: Obtaining elevation from latitude and longitude values

首先,这道题有代码。但是,它似乎只适合美国。正如他们的网站 (https://nationalmap.gov/epqs/) 所述,当无法找到价值时,它将 return -1000000,这是我的情况。

我正在尝试获取瑞典的海拔高度。

使用此样本数据:

lat = [57.728905, 57.728874, 57.728916, 57.728836, 57.728848]
lon = [11.949309, 11.949407, 11.949470, 11.949342, 11.949178]

# create df
df = pd.DataFrame({'lat': lat, 'lon': lon})

如何使下面的代码适用于全球范围,而不仅限于美国?或者至少,有什么方法可以让我专注于瑞典?美国地质调查局不应该有全球数据吗?

def make_remote_request(url: str, params: dict):
   """
   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 elevation_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']

到运行函数:

df['elevation'] = df.apply(elevation_function, axis=1)


# Print output
df

源代码:

更新:

使用已接受答案中的建议并在高程函数中添加 time.sleep(1) 使我能够获得所有观测值的高程数据。请注意,此 API 每个请求仅允许 100 个位置。因此,对于更多的行,必须将其分解为不同的请求。

我一直在使用 opentopodata.org 中的 api 来获取高程值。 您可以使用涵盖整个瑞典的 EU-DEM 数据集。 API 请求很简单,如下所示:

https://api.opentopodata.org/v1/eudem25m?locations=57.728905,11.949309

可以在 https://open-elevation.com/ 处找到另一个高度 API。请求看起来非常相似:

https://api.open-elevation.com/api/v1/lookup?locations=57.728905,11.949309

因此调整您的 elevation_function:

def elevation_function(x):
   url = 'https://api.opentopodata.org/v1/eudem25m?'
   # url = 'https://api.open-elevation.com/api/v1/lookup?'
   params = {'locations': f"{x[0]},{x[1]}"}
   result = make_remote_request(url, params)
   return result.json()['results'][0]['elevation']