欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Golang实现免费天气预报获取(OpenWeatherMap)

Golang实现免费天气预报获取(OpenWeatherMap)

2024/10/24 23:29:58 来源:https://blog.csdn.net/suwei825/article/details/140641623  浏览:    关键词:Golang实现免费天气预报获取(OpenWeatherMap)

    最近接到公司的一个小需求,需要天气数据,所以就做了一个小接口,供前端调用

    这些数据包括六个元素,如降水、风、大气压力、云量和温度。有了这些,你可以分析趋势,知道明天的数据来预测天气。

1.1 工具简介

     OpenWeatherMap可以访问地球上任何位置的当前天气数据! 我们收集和处理来自不同来源的天气数据,例如全球和本地天气模型、卫星、雷达和庞大的气象站网络。 数据以 JSON、XML 或 HTML 格式提供。

1.2 注册

主页右上角有注册入口 Members

1.3 申请key

注册登录后 默认会有一个key,你也可以增加key

在key的设置界面,可以做一些增删改操作

1.4 价格

https://openweathermap.org/price#weather

2.1 API 调用

# city name
https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}# JSON
https://api.openweathermap.org/data/2.5/weather?q=London&appid={API key}# XML
https://api.openweathermap.org/data/2.5/weather?q=London&mode=xml&appid={API key}# Latitude & Longitude
https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={API key}

2.2 API实战

    这里直接上go可运行源码,我项目中只用到温度、湿度、气压和风速,地区设置的是深圳,其它数据可自行查阅openweathermap官方api文档获取

package mainimport ("encoding/json""fmt""io/ioutil""net/http"
)type CurrentWeather struct {Main struct {Temp     float32 `json:"temp"`     // 温度Humidity float32 `json:"humidity"` // 湿度Pressure float32 `json:"pressure"` // 气压} `json:"main"`Wind struct {Speed float32 `json:"speed"` // 风速} `json:"wind"`
}func main() {// 用你的API Key替换下面的字符串apiKey := "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"location := "shenzhen"// 构造API URLurl := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", location, apiKey)// 发送HTTP GET请求resp, err := http.Get(url)if err != nil {fmt.Println("Error making request:", err)return}defer resp.Body.Close()// 读取响应体body, err := ioutil.ReadAll(resp.Body)if err != nil {fmt.Println("Error reading response body:", err)return}// 解析JSON数据var weatherData CurrentWeathererr = json.Unmarshal(body, &weatherData)if err != nil {fmt.Println("Error unmarshalling JSON:", err)return}fmt.Printf("weatherData: %.2f °C\n", weatherData)// 打印获取到的数据fmt.Printf("Temperature: %.1f °C\n", weatherData.Main.Temp)fmt.Printf("Humidity: %.2f %%\n", weatherData.Main.Humidity)fmt.Printf("Pressure: %.2f hPa\n", weatherData.Main.Pressure)fmt.Printf("Wind Speed: %.1f m/s\n", weatherData.Wind.Speed)
}

运行结果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com