.NET程序获取当前IP经纬度,并通过经纬度实现天气查询功能







{"latitude": 22.5,"longitude": 114,"generationtime_ms": 0.05698204040527344,"utc_offset_seconds": 0,"timezone": "GMT","timezone_abbreviation": "GMT","elevation": 37,"current_weather_units": {"time": "iso8601","interval": "seconds","temperature": "°C","windspeed": "km/h","winddirection": "°","is_day": "","weathercode": "wmo code"},"current_weather": {"time": "2024-10-11T09:45","interval": 900,"temperature": 26.1,"windspeed": 6.6,"winddirection": 131,"is_day": 1,"weathercode": 2}
}
- latitude: 22.5 - 纬度。表示该地点的纬度位置。
- longitude: 114 - 经度。表示该地点的经度位置。
- generationtime_ms: 0.05698204040527344 - 数据生成的时间,单位是毫秒。表示从数据请求到数据生成所用的时间。
- utc_offset_seconds: 0 - 与 UTC 时间的偏移,单位为秒。这里为 0 表示该数据是在 GMT 时区下计算的。
- timezone: "GMT" - 时区,表示为 GMT。
- timezone_abbreviation: "GMT" - 时区缩写,这里也是 GMT。
- elevation: 37 - 表示该地点的海拔高度为 37 米。
- time: "iso8601" - 时间格式遵循 ISO 8601 标准。
- interval: "seconds" - 时间间隔单位为秒。
- temperature: "°C" - 温度单位为摄氏度。
- windspeed: "km/h" - 风速单位为每小时公里数。
- winddirection: "°" - 风向单位是角度,以度数表示。
- is_day: "" - 此字段没有单位,仅用来指示是否是白天(通常为 0 或 1)。
- weathercode: "wmo code" - 表示天气情况的代码,使用 WMO(世界气象组织)标准代码。
- time: "2024-10-11T09:45" - 表示观测的具体时间点,格式为 ISO 8601,即 2024 年 10 月 11 日 09:45。此处我们要换算成自己的东八区时间,要增加8小时,则是下午17点45分。
- interval: 900 - 表示观测间隔为 900 秒,即 15 分钟。
- temperature: 26.1 - 当前温度为 26.1°C。
- windspeed: 6.6 - 当前风速为 6.6 km/h。
- winddirection: 131 - 当前风向为 131 度。风向用度数表示,0 度表示正北,90 度表示正东,131 度则大致为东南方向。
- is_day: 1 - 表示当前观测是在白天,1 代表白天,0 通常代表夜晚。
- weathercode: 2 - 当前的天气代码为 2,按照 WMO 的天气代码标准,2 通常表示“部分多云”。
- 0: 晴朗
- 1: 主要晴朗
- 2: 部分多云
- 3: 多云
- 4: 阴天
- 45: 有雾
- 48: 有浓雾
- 51: 轻微毛毛雨
- 53: 中等毛毛雨
- 55: 强毛毛雨
- 61: 轻微阵雨
- 63: 中等阵雨
- 65: 强阵雨
- 71: 轻雪
- 73: 中雪
- 75: 强雪
- 95: 雷阵雨,可能有轻微的降水
- 99: 雷阵雨,伴有强降水
LocationInfo locationInfo = null;using (var httpClient =_httpClientFactory.CreateClient())
{
httpClient.Timeout= TimeSpan.FromSeconds(100);var res = httpClient.GetAsync("http://ip-api.com/json/").GetAwaiter().GetResult();
res.EnsureSuccessStatusCode();var location =res.Content.ReadAsStringAsync().GetAwaiter().GetResult();if (!string.IsNullOrEmpty(location))
{
locationInfo= JsonConvert.DeserializeObject<LocationInfo>(location);
}
}if (locationInfo != null)
{using (var httpClient =_httpClientFactory.CreateClient())
{
httpClient.Timeout= TimeSpan.FromSeconds(100);var res = httpClient.GetAsync($"https://api.open-meteo.com/v1/forecast?latitude={locationInfo.lat}&longitude={locationInfo.lon}¤t_weather=true").GetAwaiter().GetResult();
res.EnsureSuccessStatusCode();var weather =res.Content.ReadAsStringAsync().GetAwaiter().GetResult();if (!string.IsNullOrEmpty(weather))
{
WeatherResponse weatherInfo= JsonConvert.DeserializeObject<WeatherResponse>(weather);returnOk(weatherInfo);
}
}
}
如果需要完整源码,可以在公众号【Dotnet Dancer】内回复“天气查询”即可获取源码地址。
以上就是本文章全部内容,如果有帮助,欢迎点赞、在看、转发分享或评论,谢谢大佬们捧场~