Unity 工具之 获取当前所在城市的天气数据的封装(自动定位当前所在城市,天气数据可以获得多天天数据)
目录
Unity 工具之 获取当前所在城市的天气数据的封装(自动定位当前所在城市,天气数据可以获得多天天数据)
一、简单介绍
二、实现原理
三、注意实现
四、效果预览
五、实现步骤
百度地图申请 ak:
Unity上实现:
六、关键代码
七、工程参考
八、参考文章(十分感谢这些博主的文章)
九、附:一些免费、稳定的天气预报 API 的资源参考学习
1. 国家气象局
2. 中国天气SmartWeatherAPI(/wzfw/smart/weatherapi.shtml)
3. 和风天气
4. 心知天气(免费版只提供地级市数据)
5. 彩云天气
6. 中央天气预报
一、简单介绍
Unity 工具类,自己整理的一些游戏开发可能用到的模块,单独独立使用,方便游戏开发。
本届介绍获取所在城市的天气数据,并且封装成数据接口,只要设置一个监听数据接口,即可调用。
二、实现原理
1、首先根据联网 IP 获得当前所在城市,使用百度的web API;
2、然后根据城市名称得到天气所需要的城市ID;
3、根据城市ID,最后得到天气数据,解析封装给接口调用;
三、注意实现
1、需要在百度地图开发者平台上申请一个 ak,API 和 ak 共同组成 接口,获得位置 json 解析数据
2、使用时候需要连接网络
3、接口目前好似只能获得国内的城市天气数据
四、效果预览
五、实现步骤
百度地图申请 ak:
1、登录百度地图开发者中心,需要一个百度账号,自行注册申请即可
网址:/
2、开发文档 ,选择 Web服务API
3、获取密钥(AK 应用钥匙)
4、创建应用即可获得 AK ,也可以用之前创建的(根据需要)
5、在Web服务API 普通 IP 定位中,可以看到相关使用文档,API 接口,以及返回 json 格式,等
注意 :API 和 ak 共同组成 接口,获得 json 解析数据
Unity上实现:
1、打开Unity,新建一个空工程,导入LitJson 插件
2、在场景中布局UI,展示一些天气数据
3、新建几个脚本,其中几个脚本定义一些数据结构(PositionDataStruct,WeatherDataStruct),GetWeatherWrapper 主要实现定位当前城市,和获取天气数据,TestGetWeatherWrapper 测试 GetWeatherWrapper 的接口,并展示一些天气数据
4、运行场景,效果如下
六、关键代码
1、PositionDataStruct
using System.Collections;using System.Collections.Generic;using UnityEngine;public class PositionDataStruct{public class ResponseBody{public string address;public Content content;public int status;}public class Content{public string address;public Address_Detail address_detail;public Point point;}public class Address_Detail{public string city;public int city_code;public string district;public string province;public string street;public string street_number;public Address_Detail(){}public Address_Detail(string city, int city_code, string district, string province, string street, string street_number){this.city = city;this.city_code = city_code;this.district = district;this.province = province;this.street = street;this.street_number = street_number;}}public class Point{public string x;public string y;public Point(){}public Point(string x, string y){this.x = x;this.y = y;}}}
2、WeatherDataStruct
using System.Collections;using System.Collections.Generic;using UnityEngine;public class WeatherDataStruct{public static Dictionary<string, int> PosToId = new Dictionary<string, int>();public static bool initDic = false;public const string WeatherCityId = "WeatherCityId";public static int GetWeatherId(string name){int id = 0;if(!initDic){initDic = true;TextAsset ta = Resources.Load<TextAsset>(WeatherCityId);List<Pos2Id> temp = LitJson.JsonMapper.ToObject<List<Pos2Id>>(ta.text);foreach(Pos2Id t in temp){PosToId[t.placeName] = t.id;}}for(int i=1;i<name.Length;i++){string tn = name.Substring(0, i);if(PosToId.ContainsKey(tn)){id = PosToId[tn];}}return id;}public class Pos2Id{public string placeName;public int id;public Pos2Id(){}public Pos2Id(string name,int id){placeName = name;this.id = id;}}public class WeathBody{public string time;public CityInfo cityInfo;public string date;public string message;public int status;public WeathData data;}public class CityInfo{public string city;public string citykey;public string parent;public string updateTime;}public class WeathData{public string shidu;public double pm25;public double pm10;public string quality;public string wendu;public string ganmao;public WeathDetailData yesterday;public WeathDetailData[] forecast;}public class WeathDetailData{public string date;public string sunrise;public string high;public string low;public string sunset;public double aqi;public string ymd;public string week;public string fx;public string fl;public string type;public string notice;}}
3、GetWeatherWrapper
using System;using System.Collections;using System.Collections.Generic;using UnityEngine;/// <summary>/// 获取对应城市的天气/// 注意:温度时摄氏度°C/// </summary>public class GetWeatherWrapper : MonoSingleton<GetWeatherWrapper>{/// <summary>/// 获取位置信息/// </summary>string PostionUrl = "http://api./location/ip?ak=你的百度地图申请的ak&coor=bd09ll";/// <summary>/// 获取天气/// </summary>string WeatherUrl = "http://t./api/weather/city/";Action<WeatherDataStruct.WeathBody> WeatherDataEvent;// 多少秒后更新一次数据 private float updateWeatherTime = 30;public float UpdateWeatherTime { get => updateWeatherTime; set => updateWeatherTime = value; }void Start(){//获取位置StartCoroutine(RequestPos());}/// <summary>/// 设置天气数据的监听事件/// </summary>/// <param name="WeatherDataAction"></param>public void SetWeatherDataEvent(Action<WeatherDataStruct.WeathBody> WeatherDataAction) {WeatherDataEvent = WeatherDataAction;}/// <summary>/// 获取当前所在城市/// </summary>/// <returns></returns>IEnumerator RequestPos(){WWW www = new WWW(PostionUrl);yield return www;if (string.IsNullOrEmpty(www.error)){PositionDataStruct.ResponseBody t = LitJson.JsonMapper.ToObject<PositionDataStruct.ResponseBody>(www.text);Debug.Log(t.content.address_detail.city);//获取天气StartCoroutine(RequestWeather(WeatherDataStruct.GetWeatherId(t.content.address_detail.city)));}}/// <summary>/// 获取当前所在城市的天气数据/// </summary>/// <param name="id"></param>/// <returns></returns>IEnumerator RequestWeather(int id){yield return new WaitForEndOfFrame();while (true) {WWW www = new WWW(WeatherUrl + id.ToString());Debug.Log(WeatherUrl + id.ToString());yield return www;if (string.IsNullOrEmpty(www.error)){Debug.Log(www.text);WeatherDataStruct.WeathBody t = LitJson.JsonMapper.ToObject<WeatherDataStruct.WeathBody>(www.text);Debug.Log(t.data.forecast[0].notice);if (WeatherDataEvent != null){for (int i = 0; i < t.data.forecast.Length; i++){// 正则表达式获取温度数值string low = System.Text.RegularExpressions.Regex.Replace(t.data.forecast[i].low, @"[^0-9]+", "");string high = System.Text.RegularExpressions.Regex.Replace(t.data.forecast[i].high, @"[^0-9]+", "");t.data.forecast[i].low = low;t.data.forecast[i].high = high;}WeatherDataEvent.Invoke(t);}}yield return new WaitForSeconds(updateWeatherTime);}}}
4、TestGetWeatherWrapper
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;public class TestGetWeatherWrapper : MonoBehaviour{public Text City_Text;public Text WeatherDec_Text;public Text Temperature_Text;public Text WeatherTime_Text;public Text WeatherNotice_Text;// Start is called before the first frame updatevoid Start(){ShowWeather();}void ShowWeather() {GetWeatherWrapper.Instance.SetWeatherDataEvent((weatherData)=> {City_Text.text = weatherData.cityInfo.city;WeatherTime_Text.text = weatherData.date;WeatherDec_Text.text = weatherData.data.forecast[0].type;Temperature_Text.text = weatherData.data.forecast[0].low +"°C"+ "~" + weatherData.data.forecast[0].high + "°C";WeatherNotice_Text.text = weatherData.data.forecast[0].notice;});}}
七、工程参考
下载地址:/download/u014361280/12568067
八、参考文章(十分感谢这些博主的文章)
1、/SnoopyNa2Co3/article/details/89853201
2、/p/e3e04cf3fc0f
九、附:一些免费、稳定的天气预报 API 的资源参考学习
1. 国家气象局
1)实时接口:
实时天气1:/data/sk/101190408.html
实时天气2:/data/cityinfo/101190408.html
实时天气3(带时间戳):/data/sk/101010100.html?_=1381891661455
2)一周天气预报接口
7天预报数据 URL: /data/forecast/101010100.html?_=1381891660081
该接口来源气象局移动版网站,json数据格式如下:
{"c": {"c1": "101010100", "c2": "beijing", "c3": "北京", "c4": "beijing", "c5": "北京", "c6": "beijing", "c7": "北京", "c8": "china", "c9": "中国", "c10": "1", "c11": "010", "c12": "100000", "c13": "116.391", "c14": "39.904", "c15": "33", "c16": "AZ9010", "c17": "+8"}, "f": {"f1": [{"fa": "01", "fb": "03", "fc": "10", "fd": "5", "fe": "0", "ff": "0", "fg": "0", "fh": "0", "fi": "06:21|17:40"}, {"fa": "07", "fb": "07", "fc": "19", "fd": "12", "fe": "0", "ff": "0", "fg": "0", "fh": "0", "fi": "06:22|17:38"}, {"fa": "02", "fb": "00", "fc": "15", "fd": "5", "fe": "8", "ff": "8", "fg": "3", "fh": "1", "fi": "06:23|17:37"}, {"fa": "00", "fb": "00", "fc": "16", "fd": "4", "fe": "0", "ff": "0", "fg": "0", "fh": "0", "fi": "06:24|17:35"}, {"fa": "00", "fb": "00", "fc": "18", "fd": "7", "fe": "0", "ff": "0", "fg": "0", "fh": "0", "fi": "06:25|17:34"}, {"fa": "00", "fb": "01", "fc": "18", "fd": "8", "fe": "0", "ff": "0", "fg": "0", "fh": "0", "fi": "06:26|17:32"}, {"fa": "01", "fb": "01", "fc": "16", "fd": "6", "fe": "0", "ff": "0", "fg": "0", "fh": "0", "fi": "06:27|17:31"}], "f0": "10121100"}}
详细接口分析如下:
//格式说明 var format={"fa":图片1,"fb":图片2,"fc":温度1,fd:温度2,fe:风向1,ff:风向2,fg:风力1,fh:风力2,fi:日出日落}; //定义天气类型var weatherArr={"10": "暴雨", "11": "大暴雨", "12": "特大暴雨", "13": "阵雪", "14": "小雪", "15": "中雪", "16": "大雪", "17": "暴雪", "18": "雾", "19": "冻雨", "20": "沙尘暴", "21": "小到中雨", "22": "中到大雨", "23": "大到暴雨", "24": "暴雨到大暴雨", "25": "大暴雨到特大暴雨", "26": "小到中雪", "27": "中到大雪", "28": "大到暴雪", "29": "浮尘", "30": "扬沙", "31": "强沙尘暴", "53": "霾", "99": "", "00": "晴", "01": "多云", "02": "阴", "03": "阵雨", "04": "雷阵雨", "05": "雷阵雨伴有冰雹", "06": "雨夹雪", "07": "小雨", "08": "中雨", "09": "大雨"}; //定义风向数组 var fxArr={"0": "无持续风向", "1": "东北风", "2": "东风", "3": "东南风", "4": "南风", "5": "西南风", "6": "西风", "7": "西北风", "8": "北风", "9": "旋转风"};//定义风力数组 var flArr={"0": "微风", "1": "3-4级", "2": "4-5级", "3": "5-6级", "4": "6-7级", "5": "7-8级", "6": "8-9级", "7": "9-10级", "8": "10-11级", "9": "11-12级"};
3)获取全国所有城市代码列表
方法一:XML接口根节点: /wmaps/xml/china.xmlXML接口主要作用是递归获取全国几千个县以上单位的城市代码,如:江苏的XML地址为:/wmaps/xml/shanghai.xml
苏州的XML地址为:/wmaps/xml/jiangsu.xml
上面页面获得太仓city code:101190408合成太仓天气信息地址:/data/101190408.html
下面贴一段PHP代码实现的,通过XML接口根节点递归获得全国几千个县以上城市cide code的代码,供参考(可直接在终端下运行):
方法二:一次性获取全国+国外主要城市,8763个城市列表信息。URL:/js/citylist.xml
2. 中国天气SmartWeatherAPI(/wzfw/smart/weatherapi.shtml)
1)SmartWeatherAPI接口(简称”SWA”接口)是中国气象局面向网络媒体、手机厂商、第三方气象服务机构等用户,通过web方式提供数据气象服务的官方载体。该数据主要包括预警、实况、指数、常规预报(24小时)等数据内容。
2)接口文档:/creative/SmartWeatherAPI_Lite_WebAPI_3.0.1.rar
3)使用须申请,详见官网/wzfw/smart/weatherapi.shtml
3. 和风天气
1)数据主要包含:实时天气,3天内天气预报,生活指数,空气质量。
访问流量:4000次/天。
访问频率:200次/分钟。
2)URL:https://free-/v5/forecast?city=yourcity&key=yourkey
city:城市名称,city可通过城市中英文名称、ID、IP和经纬度进行查询,经纬度查询格式为:经度,纬度。例:city=北京,city=beijing,city=CN101010100,city= 60.194.130.1
key:用户认证key
3)注册页面:/products
4)接口文档:/documents/api/v5
4. 心知天气(免费版只提供地级市数据)
1)包含数据:中国地级城市、天气实况、天气预报(3天)、生活指数(基础)。
访问频率限制:400次/小时
2)api详述:/doc
3)使用需注册。
注册地址:/signup
5. 彩云天气
1)数据包含:实时天气数据(天气、温度、湿度、风向、网速、云量、降雨量、PM2.5、空气质量指数)。
2)API详述:/index.php/%E5%BD%A9%E4%BA%91%E5%A4%A9%E6%B0%94API/v2
url示例:/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.json
/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.jsonp?callback=MYCALLBACK
3)使用需注册
产品详单:/api/caiyun_api_service_price.pdf
注册页面:/dev_center/regist.html
6. 中央天气预报
1)url:/Heart/index/all
参数如下:
city:城市码
language:固定值 zh-chs
unit:温度单位固定值 c。可不填。也可省略该参数
aqi:固定值 city。可不填。也可省略该参数
alarm:固定值 1。可不填。也可省略该参数
key:秘钥,固定值 78928e706123c1a8f1766f062bc8676b。可不填。也可省略该参数
url 示例:/Heart/index/all?city=CHSH000000&language=zh-chs&unit=c&aqi=city&alarm=1&key=78928e706123c1a8f1766f062bc8676b
或 /Heart/index/all?city=CHSH000000&language=&unit=&aqi=&alarm=&key=
或 /Heart/index/all?city=CHSH000000
json 示例:
{"status": "OK","weather": [{"city_name": "佛山","city_id": "CHGD070000","last_update": "-02-19T12:15:00+08:00","now": {"text": "阴","code": "9","temperature": "21","feels_like": "21","wind_direction": "南","wind_speed": "10.44","wind_scale": "2","humidity": "58","visibility": "13.8","pressure": "1014","pressure_rising": "未知","air_quality": {"city": {"aqi": "64","pm25": "46","pm10": "74","so2": "9","no2": "28","co": "0.575","o3": "108","last_update": "-02-19T12:00:00+08:00","quality": "良"},"stations": null}},"today": {"sunrise": "06:58 AM","sunset": "6:27 PM","suggestion": {"dressing": {"brief": "单衣类","details": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。"},"uv": {"brief": "最弱","details": "属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。"},"car_washing": {"brief": "不适宜","details": "不宜洗车,未来24小时内有雨,如果在此期间洗车,雨水和路上的泥水可能会再次弄脏您的爱车。"},"travel": {"brief": "适宜","details": "天气较好,温度适宜,总体来说还是好天气哦,这样的天气适宜旅游,您可以尽情地享受大自然的风光。"},"flu": {"brief": "易发期","details": "相对今天出现了较大幅度降温,较易发生感冒,体质较弱的朋友请注意适当防护。"},"sport": {"brief": "比较适宜","details": "阴天,较适宜进行各种户内外运动。"}}},"future": [{"date": "-02-19","day": "周日","text": "阴/小雨","code1": "9","code2": "13","high": "24","low": "18","cop": "","wind": "微风3级"},{"date": "-02-20","day": "周一","text": "阴","code1": "9","code2": "9","high": "23","low": "18","cop": "","wind": "微风3级"},{"date": "-02-21","day": "周二","text": "阵雨","code1": "10","code2": "10","high": "22","low": "18","cop": "","wind": "微风3级"},{"date": "-02-22","day": "周三","text": "小雨","code1": "13","code2": "13","high": "23","low": "13","cop": "","wind": "微风3级"},{"date": "-02-23","day": "周四","text": "小雨","code1": "13","code2": "13","high": "20","low": "10","cop": "","wind": "北风4级"},{"date": "-02-24","day": "周五","text": "小雨","code1": "13","code2": "13","high": "14","low": "10","cop": "","wind": "北风4级"},{"date": "-02-25","day": "周六","text": "小雨","code1": "13","code2": "13","high": "15","low": "10","cop": "","wind": "微风3级"},{"date": "-02-26","day": "周日","text": "小雨","code1": "13","code2": "13","high": "15","low": "10","cop": "","wind": "北风3级"},{"date": "-02-27","day": "周一","text": "小雨/多云","code1": "13","code2": "4","high": "21","low": "11","cop": "","wind": "北风3级"},{"date": "-02-28","day": "周二","text": "多云","code1": "4","code2": "4","high": "24","low": "14","cop": "","wind": "北风3级"}]}]}
解析:
status:成功时返回 OKweather:天气信息city_name:城市名city_id:城市 idlast_update:上次更新时间now:现在天气状况text:天气状况code:???temperature:温度feels_like:体感温度wind_direction:风向wind_speed:风速wind_scale:风力大小humidity:空气湿度visibility:能见度,单位为 kmpressure:气压,单位为 hPaair_quality:具体空气质量指数aqi:空气质量指数pm25:pm2.5指数pm10:pm10指数so2:二氧化硫指数no2:二氧化氮指数co:一氧化碳指数o3:臭氧指数last_update:上次更新时间quality:空气质量today:今日天气状况sunrise:日出时间sunset:日落时间suggestion:建议列表dressing:穿衣信息uv:紫外线建议car_washing:洗车信息travel:旅游信息flu:流感信息sport:运动信息brief:建议、说明details:具体信息future:未来天气状况列表date:日期day:周几text:天气状况code1:???code2:???high:当日最高气温low:当日最低气温cop:???wind:风力信息
2)24小时天气预报
url:/Heart/index/future24h/
拼接参数:
city:城市
language:语言
key:秘钥,固定值 78928e706123c1a8f1766f062bc8676b。可不填。也可省略该参数
url 示例:/Heart/index/future24h/?city=CHSH000000&language=zh-chs&
key=36bdd59658111bc23ff2bf9aaf6e345c
或 /Heart/index/future24h/?city=CHSH000000&language=&key=
或 /Heart/index/future24h/?city=CHSH000000
json示例
{"status": "OK","hourly": [{"text": "多云","code": "4","temperature": "16","time": "-02-19T13:00:00+08:00"},{"text": "多云","code": "4","temperature": "18","time": "-02-19T14:00:00+08:00"},{"text": "多云","code": "4","temperature": "17","time": "-02-19T15:00:00+08:00"},{"text": "多云","code": "4","temperature": "16","time": "-02-19T16:00:00+08:00"},{"text": "多云","code": "4","temperature": "16","time": "-02-19T17:00:00+08:00"},{"text": "多云","code": "4","temperature": "16","time": "-02-19T18:00:00+08:00"},{"text": "多云","code": "4","temperature": "15","time": "-02-19T19:00:00+08:00"},{"text": "多云","code": "4","temperature": "15","time": "-02-19T20:00:00+08:00"},{"text": "多云","code": "4","temperature": "15","time": "-02-19T21:00:00+08:00"},{"text": "多云","code": "4","temperature": "14","time": "-02-19T22:00:00+08:00"},{"text": "多云","code": "4","temperature": "14","time": "-02-19T23:00:00+08:00"},{"text": "多云","code": "4","temperature": "14","time": "-02-20T00:00:00+08:00"},{"text": "多云","code": "4","temperature": "15","time": "-02-20T01:00:00+08:00"},{"text": "小雨","code": "13","temperature": "15","time": "-02-20T02:00:00+08:00"},{"text": "小雨","code": "13","temperature": "15","time": "-02-20T03:00:00+08:00"},{"text": "小雨","code": "13","temperature": "15","time": "-02-20T04:00:00+08:00"},{"text": "中雨","code": "14","temperature": "15","time": "-02-20T05:00:00+08:00"},{"text": "中雨","code": "14","temperature": "13","time": "-02-20T06:00:00+08:00"},{"text": "中雨","code": "14","temperature": "10","time": "-02-20T07:00:00+08:00"},{"text": "小雨","code": "13","temperature": "8","time": "-02-20T08:00:00+08:00"},{"text": "小雨","code": "13","temperature": "6","time": "-02-20T09:00:00+08:00"},{"text": "小雨","code": "13","temperature": "5","time": "-02-20T10:00:00+08:00"},{"text": "小雨","code": "13","temperature": "5","time": "-02-20T11:00:00+08:00"},{"text": "小雨","code": "13","temperature": "6","time": "-02-20T12:00:00+08:00"}]}
解析
status:成功时返回 OKhourly:具体小时天气信息列表text:天气状况code:请参考 [code 细节]temperature:温度time:时间
另 ,code细节
/// 晴case sunny = 0/// 晴case clear = 1/// 晴case fair1 = 2/// 晴case fair2 = 3/// 多云case cloudy = 4/// 晴间多云case partlyCloudy1 = 5/// 晴间多云case partlyCloudy2 = 6/// 大部多云case mostlyCloudy1 = 7/// 大部多云case mostlyCloudy2 = 8/// 阴case overcast = 9/// 阵雨case shower = 10/// 雷阵雨case thundershower = 11/// 雷阵雨伴有冰雹case thundershowerWithHail = 12/// 小雨case lightRain = 13/// 中雨case moderateRain = 14/// 大雨case heavyRain = 15/// 暴雨case storm = 16/// 大暴雨case heavyStorm = 17/// 特大暴雨case severeStorm = 18/// 冻雨case iceRain = 19/// 雨夹雪case sleet = 20/// 阵雪case snowFlurry = 21/// 小雪case lightSnow = 22/// 中雪case moderateSnow = 23/// 大雪case heavySnow = 24/// 暴雪case snowstorm = 25/// 浮尘case dust = 26/// 扬沙case sand = 27/// 沙尘暴case duststorm = 28/// 强沙尘暴case sandstorm = 29/// 雾case foggy = 30/// 霾case haze = 31/// 风case windy = 32/// 大风case blustery = 33/// 飓风case hurricane = 34/// 热带风暴case tropicalStorm = 35/// 龙卷风case tornado = 36/// 冷case cold = 37/// 热case hot = 38/// 未知case unknown = 99
Unity 工具之 获取当前所在城市的天气数据的封装(自动定位当前所在城市 天气数据可以获得多天天数据)