Unity获取当前城市天气

来源:互联网 发布:网络直播评论性文章 编辑:程序博客网 时间:2024/05/21 12:20

完善了根据当前IP查询所在城市编码,然后根据城市编码获取当前城市天气,DEMO下载地址

参考http://blog.csdn.net/wjb0108/article/details/41380193
效果:   
代码如下:
using UnityEngine;  using System.Collections;  using System.IO;  using LitJson;using System.Text.RegularExpressions;using System.Xml;using System.Text;public class WeatherTest : MonoBehaviour{       private string m_url = "http://www.weather.com.cn/data/cityinfo/";//上海天气  101210101.html    public string lbCity;//城市      public string lbTemperature;//温度      public string lbWeahter;//天气      public string lbTime;    public string lbHour;    public string lbMinute;    public string lbColon;    private System.DateTime dNow;    private string[] dow = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };    private float deltaTime = 0.0f; //update Date      private float deltaTimeforWeather = 0.0f; // update Weather      private float howlongToUpdate = 3600f;    void Start()    {        StartCoroutine(GetExternalIp());    }    void Update()    {        //Date          dNow = System.DateTime.Now;        lbTime = dNow.ToString("yyyy年MM月dd日 HH:mm:ss  ") + dow[System.Convert.ToInt16(dNow.DayOfWeek)];        lbHour = dNow.ToString("HH");        lbMinute = dNow.ToString("mm");        deltaTime += Time.deltaTime;        if (deltaTime > 1.0f)        {            deltaTime = 0.0f;        }        deltaTimeforWeather += Time.deltaTime;        if (deltaTimeforWeather > howlongToUpdate)//每一小时更新一次          {            UpdateWeather();            deltaTimeforWeather = 0.0f;        }    }    public void UpdateWeather()    {        StartCoroutine(GetWeather(CityCodeId));    }    //void OnEnable()    //{    //    UpdateWeather();    //}    IEnumerator GetWeather(string CityId)//根据城市ID获取天气信息    {        if (m_url != null)        {            WWW www = new WWW(m_url + CityId + @".html");            Debug.Log("URL:"+m_url + CityId + @".html");            while (!www.isDone) { yield return www; }            if (www.text != null)            {                JsonData jd = JsonMapper.ToObject(www.text);                JsonData jdInfo = jd["weatherinfo"];                lbCity = jdInfo["city"].ToString();                lbTemperature = jdInfo["temp1"].ToString() + "~" + jdInfo["temp2"].ToString();                lbWeahter = jdInfo["weather"].ToString();                //。。。。需要的其它信息自己看接口提取                string strImg1 = jdInfo["img1"].ToString();                Debug.Log("city:" + lbCity + "\n weather:" + lbWeahter);            }        }    }    string ip;    IEnumerator GetExternalIp()//获取当前外网地址    {        WWW www = new WWW("http://www.ip138.com/ips138.asp");        while (!www.isDone) { yield return www; }        if (www.text != null)        {                       Regex r = new Regex("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])", RegexOptions.None);            Match mc = r.Match(www.text);            ip = mc.Groups[0].Value;            MacIp = ip;            StartCoroutine(GetAdrByIp());        }    }    string MacIp;    IEnumerator GetAdrByIp()//根据IP获取当前城市地址    {        //string url = "http://www.ip138.com/ips138.asp?ip=" + MacIp;        string url = "http://www.ip.cn/index.php?ip=" + MacIp;        string regStr = "(?<=<div\\s*id=\\\"result\\\">).*?(?=</div>)";        WWW html = new WWW(url.Trim());        print("IP查询地址:"+url);        while (!html.isDone) { yield return html; }                if (html.text != null)        {            Regex reg = new Regex(regStr, RegexOptions.None);            Match ma = reg.Match(html.text);                        City = ma.Value;                        string resstr;            resstr = (ReplaceHtmlTag(City).Trim().Split(':')[2].Substring(0, 6)).ToString();            print(resstr);            string[] arr = resstr.Split('省');            Province = arr[0];            City = arr[1].Replace("市", null); Debug.Log("内容:" + City);            Xmlfilepath = Application.dataPath + @"/CityWeather/CityCode.xml";            CityCodeId = ReadXml(Xmlfilepath, City, Province);            Debug.Log(Province + "省" + City + CityCodeId);            UpdateWeather();        }    }    string Xmlfilepath;    string City;    string Province;    string CityCodeId;    public string ReadXml(string filepath, string value, string province)    {        string strvalue = null;        if (File.Exists(filepath))        {            XmlDocument xmlDoc = new XmlDocument();            xmlDoc.Load(filepath);            XmlNodeList nodeList = xmlDoc.SelectSingleNode("China").ChildNodes;            foreach (XmlElement xe in nodeList)            {                if (xe.GetAttribute("name") == province)                {                    foreach (XmlElement x1 in xe.ChildNodes)                    {                        foreach (XmlElement x2 in x1.ChildNodes)                        {                            if (x2.GetAttribute("name") == value)                            {                                strvalue = x2.GetAttribute("weatherCode");                            }                        }                    }                }            }        }         return strvalue;    }    public static string ReplaceHtmlTag(string html, int length = 0)//移除HTML标签    {        string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");        strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");        if (length > 0 && strText.Length > length)            return strText.Substring(0, length);        return strText;    }      void OnGUI()    {        GUI.Label(new Rect(60, 40, 200, 25),  "公 网 IP :" + ip);        GUI.Label(new Rect(60, 70, 200, 25),  "所在城市 :" + Province + "省" + City + "市");        GUI.Label(new Rect(60, 130, 200, 25), "城市编码:" + CityCodeId);        GUI.Label(new Rect(60, 160, 200, 25), "城市天气:" + lbWeahter);        GUI.Label(new Rect(60, 190, 200, 25), "城市气温:" + lbTemperature);        GUI.Label(new Rect(60, 100, 300, 25), "城市时间:" + lbTime);        }}    


 
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 苹果7后壳氧化怎么办 苹果6s后盖氧化怎么办 苹果6s后壳氧化怎么办 食道癌吃了就吐怎么办 有眼袋和泪沟怎么办? 泪沟和眼袋都有怎么办 脸上的汗毛很长怎么办 点痣留下褐色印怎么办 氮氧传感器坏了怎么办 考试车离合太松怎么办 胎心监护不过关怎么办 羚羊角的功效与作用发烧怎么办 小孩上课注意力不集中怎么办 2岁宝宝不会说话怎么办 小孩脖子上长淋巴结怎么办 小孩子上课注意力不集中该怎么办 脸过敏干燥起皮怎么办 脸上皮肤干燥起皮怎么办 身上皮肤干燥起皮怎么办 皮肤暗黄有色斑怎么办 我皮肤干燥暗黄怎么办 脸上有皮肤暗黄怎么办 皮肤暗黄毛孔大怎么办 脸上很干燥起皮怎么办 脸上的皮肤起皮怎么办 身体的皮肤好干怎么办 滴油雾化器炸油怎么办 已经发炎的痘痘怎么办 被养生馆骗了怎么办 做完微针结痂了怎么办 秋季脸干燥起皮怎么办 身上的皮肤太干怎么办 板材眼镜腿松了怎么办 超声刀后喝酒了怎么办 开眼角疤痕增生了怎么办 开了眼角有增生怎么办 全切双眼皮留疤怎么办 开内眼角留疤了怎么办 开眼角长了颗粒怎么办 开刀后疤痕庝痛怎么办 眼角开得太尖了怎么办