我正在尝试创建一个程序,该程序从离我最近的位置检索天气信息。然后,我似乎注意到成功之后是该程序将使用第一个可用的气象数据选项,该选项位于约6,373公里之外。有人有建议吗?注意:出于隐私原因,我将坐标替换为x。您可以插入自己的坐标,程序应该可以运行。我也是python的新手,所以请尽量不要使您的答案过于复杂。
from requests import get
import json
from pprint import pprint
from haversine import haversine
stations = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getallstations'
weather = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getlatestmeasurements/'
my_lat = x
my_lon = x
all_stations = get(stations).json()['items']
def find_closest():
smallest = 20036
for station in all_stations:
station_lon = station['weather_stn_long']
station_lat = station['weather_stn_lat']
distance = haversine(my_lon, my_lat, station_lon, station_lat)
if distance < smallest:
smallest = distance
closest_station = station['weather_stn_id']
print(distance)
return closest_station
closest_stn = find_closest()
weather = weather + str(closest_stn)
my_weather = get(weather).json()['items']
pprint(my_weather)
答案 0 :(得分:1)
return closest_station
不应在循环中。这会使函数在第一次迭代时返回,而不是在您遍历所有测站之后返回。
该行应与for
语句具有相同的缩进,以便在循环完成后执行。