使用Google Weather API查詢天氣預報
Google Weather API 只支援美國地區使用郵遞區號進行查詢,例如:
http://www.google.com/ig/api?hl=zh-cn&weather=94043
(94043 為 山景城, 美國加州 的郵遞區號)
而除了美國以外的地區需要使用經緯度座標作為參數才能執行 Google Weather API, 例如:
http://www.google.com/ig/api?hl=zh-cn&weather=,,,30670000,104019996
(30670000,104019996 為 成都, 中國大陸 的經緯度座標)
當然,也可能通行城市名稱的漢語拼音來查詢,例如:以下是北京的天氣
http://www.google.com/ig/api?hl=zh-cn&weather=Beijing
要其它地區的經緯度座標,可以通過 Google API 提供的國家代碼清單及相應的城市經緯度座標列表可以查詢到,以下是 Google API 提供的查詢參數:
http://www.google.com/ig/countries?output=xml&hl=zh-cn
(查詢 Google 所支援的所有國家的代碼,並以 zh-cn 簡體中文顯示)
http://www.google.com/ig/cities?output=xml&hl=zh-cn&country=cn
C#範例:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
namespace GoogleWeatherAPI_Parser
{
class Program
{
static void Main(string[] args)
{
int i = 0;
XmlNodeList GWP_NodeList = GoogleWeatherAPI_Parser(@"http://www.google.co.uk/ig/api?weather=Drammen").SelectNodes("xml_api_reply/weather/current_conditions");
Console.WriteLine("Current weather in Drammen: " + GWP_NodeList.Item(i).SelectSingleNode("temp_c").Attributes["data"].InnerText);
Console.ReadLine();
}
private static XmlDocument GoogleWeatherAPI_Parser(string baseUrl)
{
HttpWebRequest GWP_Request;
HttpWebResponse GWP_Response = null;
XmlDocument GWP_XMLdoc = null;
try
{
GWP_Request = (HttpWebRequest)WebRequest.Create(string.Format(baseUrl));
GWP_Request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
GWP_Response = (HttpWebResponse)GWP_Request.GetResponse();
GWP_XMLdoc = new XmlDocument();
GWP_XMLdoc.Load(GWP_Response.GetResponseStream());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
GWP_Response.Close();
return GWP_XMLdoc;
}
}
}
附:其它天氣API
Yahoo:http://developer.yahoo.com/weather/
北京天氣(可以通過搜尋尋找)
http://xml.weather.yahoo.com/forecastrss?p=CHXX0008&u=f
國內API:
北京天氣
http://weather.all2rss.com/weatherrss.asp?City=北京