2025-01-22 16:50:00 +08:00
|
|
|
# app/services/weather_service.rb
|
|
|
|
class WeatherService
|
|
|
|
include HTTParty
|
2025-01-22 17:07:04 +08:00
|
|
|
base_uri Rails.application.credentials.dig(:qweather, :uri)
|
2025-01-22 16:50:00 +08:00
|
|
|
|
|
|
|
def initialize
|
|
|
|
@api_key = Rails.application.credentials.qweather.token
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_weather(latitude, longitude)
|
|
|
|
Rails.logger.debug "Get Weather for #{latitude},#{longitude}"
|
|
|
|
response = self.class.get(
|
|
|
|
"/weather/now",
|
|
|
|
headers: {
|
|
|
|
"X-QW-Api-Key" => "#{@api_key}"
|
|
|
|
},
|
|
|
|
query: {
|
|
|
|
location: "#{longitude},#{latitude}"
|
|
|
|
})
|
|
|
|
|
|
|
|
return nil unless response.success?
|
|
|
|
|
|
|
|
data = response["now"]
|
|
|
|
{
|
|
|
|
temperature: data["temp"].to_f,
|
|
|
|
feeling_temp: data["feelsLike"].to_f,
|
|
|
|
humidity: data["humidity"].to_f,
|
|
|
|
wind_scale: "#{data['windScale']}级",
|
|
|
|
wind_speed: data["windSpeed"].to_f,
|
|
|
|
precipitation: data["precip"].to_f,
|
|
|
|
pressure: data["pressure"].to_f,
|
|
|
|
visibility: data["vis"].to_f,
|
|
|
|
cloud: data["cloud"].to_f,
|
2025-01-31 10:46:32 +08:00
|
|
|
description: data["text"],
|
|
|
|
time: response["updateTime"]
|
2025-01-22 16:50:00 +08:00
|
|
|
}
|
|
|
|
end
|
|
|
|
end
|