[ASP.NET]使用google weather api取得氣象資料

[ASP.NET]使用google weather api取得氣象資料

正好要解決之前的需求有用到

api使用的方式可以google一下有很多

紀錄一下步驟

 

STEP1 建立氣象資料表格

先在網址列輸入 http://www.google.com/ig/cities?country=TW

可以看到台灣地區城市的經緯度列表

pic1

利用列表建立TABLE(GoogleMapAxis) , 其中Priority欄位用來畫面顯示排序使用

pic2

 

STEP2 建立氣象資料物件檔

程式如下


using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Xml;
using System.IO;
using System.Data;

/// <summary>
/// Google氣象資料
/// </summary>
public class GoogleWeatherData
{
    /// <summary>
    /// Gets or sets the city.
    /// </summary>
    /// <value>
    /// The city.
    /// </value>
    public string city { get; set; }
    /// <summary>
    /// Gets or sets the temperature.
    /// </summary>
    /// <value>
    /// The temperature.
    /// </value>
    public string temperature { get; set; }
    /// <summary>
    /// Gets or sets the weather DES.
    /// </summary>
    /// <value>
    /// The weather DES.
    /// </value>
    public string weatherDes { get; set; }
    /// <summary>
    /// Gets or sets the weather pic.
    /// </summary>
    /// <value>
    /// The weather pic.
    /// </value>
    public string weatherPic { get; set; }
    /// <summary>
    /// Gets or sets the wind condition.
    /// </summary>
    /// <value>
    /// The wind condition.
    /// </value>
    public string windCondition { get; set; }
    /// <summary>
    /// Gets or sets the humidity.
    /// </summary>
    /// <value>
    /// The humidity.
    /// </value>
    public string humidity { get; set; }
    /// <summary>
    /// Initializes a new instance of the <see cref="GoogleWeatherData"/> class.
    /// </summary>
    /// <param name="location">The location.</param>
    /// <param name="lat">The lat.</param>
    /// <param name="lon">The lon.</param>
    public GoogleWeatherData(string location, string lat, string lon)
    {
        //
        // TODO: 在此加入建構函式的程式碼
        //
        GetWeather(location, lat, lon);
    }
    /// <summary>
    /// Gets the weather.
    /// </summary>
    /// <param name="location">The location.</param>
    /// <param name="lat">The lat.</param>
    /// <param name="lon">The lon.</param>
    private void GetWeather(string location, string lat, string lon)
    {
        city = location;
        HttpWebRequest GoogleRequest;
        HttpWebResponse GoogleResponse = null;
        XmlDocument GoogleXMLdoc = null;
        string weather = string.Empty;

        try
        {
            GoogleRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api?output=xml&hl=zh-tw&weather=,,," + lat + "," + lon);
            GoogleResponse = (HttpWebResponse)GoogleRequest.GetResponse();
            GoogleXMLdoc = new XmlDocument();
            GoogleXMLdoc.XmlResolver = null;
            StreamReader reader = new StreamReader(GoogleResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("big5"));
            GoogleXMLdoc.Load(reader);
            string url = @"http://www.google.com";
            XmlNode root = GoogleXMLdoc.DocumentElement;
            XmlNodeList nodeList1 = root.SelectNodes("weather/forecast_information");
            //weather = weather + "<b>城市: " + nodeList1.Item(0).SelectSingleNode("city").Attributes["data"].InnerText + "</b>";
            XmlNodeList nodeList = root.SelectNodes("weather/current_conditions");

            temperature = nodeList.Item(0).SelectSingleNode("temp_c").Attributes["data"].InnerText + " °C";
            weatherDes = nodeList.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText;
            weatherPic = url + nodeList.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText;
            windCondition = nodeList.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerText;
            humidity = nodeList.Item(0).SelectSingleNode("humidity").Attributes["data"].InnerText;
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
        finally
        {
            GoogleResponse.Close();
        }
    }


}



/// <summary>
/// Google氣象資料集合物件
/// </summary>
public class GoogleWeatherCollect
{
    private List<GoogleWeatherData> googleWeatherData = new List<GoogleWeatherData>();

    public GoogleWeatherCollect()
    {

    }

    /// <summary>
    /// Initials the data.
    /// </summary>
    public void InitialData()
    {
        string name, lat, lon;

        foreach (DataRow dr in GetCityList().Rows)
        {
            name = dr["name"].ToString();
            lat = dr["lat"].ToString();
            lon = dr["lon"].ToString();
            googleWeatherData.Add(new GoogleWeatherData(name, lat, lon));
        }
    }
    /// <summary>
    /// Gets the city list.
    /// </summary>
    /// <returns></returns>
    private DataTable GetCityList()
    {
        string sqlcmd = " select name,lat,lon from iom..GoogleMapAxis order by Priority ";
        DataAccessLayer dal = new DataAccessLayer();
        return dal.GetQueryResultToDataTable(sqlcmd, null);
    }
    /// <summary>
    /// Gets the weather data.
    /// </summary>
    /// <returns></returns>
    public List<GoogleWeatherData> GetWeatherData()
    {
        return googleWeatherData;
    }
}

 

 

STEP3 設計頁面

ASPX



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title></title>
	<style type="text/css">
		a{
			color:#b03117;
			font-size:9pt;  
			text-decoration: none;  
			vertical-align: middle
		}        
		td{
			height: 9pt;
			border: 0px;
			color:#b03117;
		}
	</style>
</head>
<body>
	<form id="form1" runat="server">
	<div>
	
		<asp:Label ID="lbl_Weather" runat="server"></asp:Label>
	
	</div>

	<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
        SelectMethod="GetWeatherData" TypeName="GoogleWeatherCollect">
    </asp:ObjectDataSource>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        onrowcreated="GridView1_RowCreated">
        <Columns>
            <asp:BoundField DataField="city" HeaderText="城市" SortExpression="city" />
            <asp:BoundField DataField="temperature" HeaderText="溫度" 
                SortExpression="temperature" />
            <asp:TemplateField HeaderText="天氣" SortExpression="weatherDes">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("weatherDes") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("weatherDes") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField ShowHeader="False" SortExpression="weatherPic">
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("weatherPic") %>' />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("weatherPic") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="windCondition" HeaderText="風向" 
                SortExpression="windCondition" />
            <asp:BoundField DataField="humidity" HeaderText="濕度" 
                SortExpression="humidity" />
        </Columns>
    </asp:GridView>

	</form>
</body>
</html>

CS


using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Xml;
using System.IO;
using System.Data;
using System.Text;

/// <summary>
/// 使用google api 讀取天氣資料
/// http://www.aspx2.com/Article/View/237828
/// http://ssd910.blog.163.com/blog/static/238767972010613257484/
/// </summary>
public partial class Weather : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        GoogleWeatherCollect collect = new GoogleWeatherCollect();
        collect.InitialData();
        GridView1.DataSource = collect.GetWeatherData();
        GridView1.DataBind();
    }

    /// <summary>
    /// 合併表頭(天氣).
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells.RemoveAt(3);
            e.Row.Cells[2].ColumnSpan = 2;
        }
    }
}

這樣就OK了

產出畫面

pic3

最後附上Google Map查經緯度的方法

先輸入地點查詢後

按右鍵選”這裡有甚麼”

pic4

在搜尋列就會出現經緯度了

如果要在google weather使用要拿掉小數點

pic5

 

參考資料

使用Google Weather API获取天气预报,中文支持

google 天氣 api 作者: 丫忠

使用Google Weather API查询天气预报

如何使用 Google map 查找經緯度給Mobiel01景點座標