이번 포스트에서는 구글에서 제공하는 날씨에 관련된 API를 사용하여 화면에 출력하는 방법을 설명하도록 하겠습니다.
이 포스트는 Animaonline's Nerdy Corner의 포스트를 참고로 만들었습니다.
구글에서 제공하는 날씨 API를 호출하는 방법은 다음과 같이 간단합니다.
http://www.google.co.kr/ig/api?weather=seoul
한 눈에 보이다시피, weather라는 쿼리스트링 변수에 조회하려고 하는 도시를 입력해주시면 됩니다. 다만, 사람들이 많이 살고 있는 큰 도시만 가능하며, 다른 국가의 도시를 조회할 경우에는 www.google.co.kr 이 아닌 www.google.com 으로 해주시면, 자동적으로 그 나라의 도메인으로 변경되어 조회하려고 하는 도시의 정보를 가져올 수 있습니다.
위에서 설명드린 URL을 바탕으로 쿼리를 하면 다음과 같은 XML 형식이 화면에 출력됩니다.

그림 1. 날씨 정보가 포함된 XML
여기에서 날씨 정보에 관련된 항목은 <current_conditions>입니다. 나머지 항목은 필요할 경우 사용하면 되겠습니다.
이제, 서울과 부산의 날씨 정보를 출력하도록 하겠습니다. 웹 폼에 다음과 같이 코드를 작성합니다.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Weather.aspx.cs" Inherits="Weather" Debug="true" %>
<!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>
</head>
<body>
<form id="WeatherForm" runat="server">
<table border="0" cellpadding="0" cellspacing="0" style="background-color:#959695;" width="600px">
<tr style="height: 24px" valign="middle">
<td style="width: 100%; font-size: 11pt; color: White;" align="center" colspan="2">
Weather Info
</td>
</tr>
<tr style="height: 24px" valign="middle">
<td style="width: 30%; background-color: White; font-size: 9pt;border-left:1px solid #959695;border-right:1px solid #959695;" align="center">
서울의 날씨
</td>
<td style="width: 70%; background-color: White; font-size: 9pt;border-right:1px solid #959695;padding:10px;" align="left">
<asp:Image ID="imgSeoul" runat="server" ImageAlign="absMiddle" /><br />
현재 상태 : <asp:Label ID="lblSeoulCondition" runat="server"></asp:Label><br />
섭씨 온도 : <asp:Label ID="lblSeoulTempf" runat="server"></asp:Label><br />
화씨 온도 : <asp:Label ID="lblSeoulTempc" runat="server"></asp:Label><br />
<asp:Label ID="lblSeoulHumidity" runat="server"></asp:Label><br />
<asp:Label ID="lblSeoulWind" runat="server"></asp:Label>
</td>
</tr>
<tr style="height: 1px" valign="middle">
<td style="width: 100%;" align="center" colspan="2">
</td>
</tr>
<tr style="height: 24px" valign="middle">
<td style="width: 30%; background-color: White; font-size: 9pt;border-left:1px solid #959695;border-right:1px solid #959695;" align="center">
부산의 날씨
</td>
<td style="width: 70%; background-color: White; font-size: 9pt;border-right:1px solid #959695;padding:10px;" align="left">
<asp:Image ID="imgPusan" runat="server" ImageAlign="absMiddle" /><br />
현재 상태 : <asp:Label ID="lblPusanCondition" runat="server"></asp:Label><br />
섭씨 온도 : <asp:Label ID="lblPusanTempf" runat="server"></asp:Label><br />
화씨 온도 : <asp:Label ID="lblPusanTempc" runat="server"></asp:Label><br />
<asp:Label ID="lblPusanHumidity" runat="server"></asp:Label><br />
<asp:Label ID="lblPusanWind" runat="server"></asp:Label>
</td>
</tr>
<tr style="height: 1px" valign="middle">
<td style="width: 100%;" align="center" colspan="2">
</td>
</tr>
</table>
</form>
</body>
</html>
웹 폼에서 서울과 부산의 날씨에 대한 정보를 Image 컨트롤과 Label 컨트롤을 사용하여 화면에 보여지도록 코드를 작성하였습니다. 다음으로는 코드 비하인드의 코드입니다.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Net;
/*---------------------------------------------------------------------------------------------------
* Creator : Neostyx
* CreateDate : 2007-07-27
* HomePage : http://www.neostyx.net
* Goal : Gaining the Weather of Local's City
---------------------------------------------------------------------------------------------------*/
public partial class Weather : System.Web.UI.Page
{
private const string _googleUrl = "http://www.google.co.kr";
protected void Page_Load(object sender, EventArgs e)
{
GetWeatherData(_googleUrl + "/ig/api?weather=seoul", imgSeoul, lblSeoulCondition, lblSeoulTempf, lblSeoulTempc, lblSeoulHumidity, lblSeoulWind);
GetWeatherData(_googleUrl + "/ig/api?weather=pusan", imgPusan, lblPusanCondition, lblPusanTempf, lblPusanTempc, lblPusanHumidity, lblPusanWind);
}
private void GetWeatherData(string strCityUrl, Image imgWeather, Label lblCityCondition, Label lblCityTempf, Label lblCityTempc, Label lblCityHumidity, Label lblCityWind)
{
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(String.Format(strCityUrl));
httpReq.UserAgent = Request.ServerVariables["HTTP_USER_AGENT"].ToString();
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(httpRes.GetResponseStream());
httpRes.Close();
XmlNode xWeatherNode = xmlDoc.SelectSingleNode("xml_api_reply/weather/current_conditions");
if (xWeatherNode != null)
{
imgWeather.ImageUrl = _googleUrl + xWeatherNode.SelectSingleNode("icon").Attributes["data"].Value;
lblCityCondition.Text = xWeatherNode.SelectSingleNode("condition").Attributes["data"].Value;
lblCityTempf.Text = xWeatherNode.SelectSingleNode("temp_f").Attributes["data"].Value;
lblCityTempc.Text = xWeatherNode.SelectSingleNode("temp_c").Attributes["data"].Value;
lblCityHumidity.Text = xWeatherNode.SelectSingleNode("humidity").Attributes["data"].Value;
lblCityWind.Text = ReplaceFromHanToEng(xWeatherNode.SelectSingleNode("wind_condition").Attributes["data"].Value);
}
xmlDoc = null;
}
private string ReplaceFromHanToEng(string strEng)
{
strEng = strEng.Replace("N", "북");
strEng = strEng.Replace("E", "동");
strEng = strEng.Replace("W", "서");
strEng = strEng.Replace("S", "동");
return strEng;
}
}
코드에 대한 설명을 간단히 드리도록 하겠습니다.
HttpWebRequest, HttpWebResponse 클래스를 사용하기 위해 System.Net 네임스페이스와 XmlDocument 클래스를 사용하기 위해 System.Xml 클래스를 using 문에 추가하였습니다.
using System.Xml;
using System.Net;
그리고 상수 _googleUrl에는 구글의 기본 주소를 할당한 후 Load 이벤트에서 GetWeatherData() 메소드를 호출하여 각각 서울과 부산의 날씨 정보를 구하도록 하였습니다.
private const string _googleUrl = "http://www.google.co.kr";
protected void Page_Load(object sender, EventArgs e)
{
GetWeatherData(_googleUrl + "/ig/api?weather=seoul", imgSeoul, lblSeoulCondition, lblSeoulTempf, lblSeoulTempc, lblSeoulHumidity, lblSeoulWind);
GetWeatherData(_googleUrl + "/ig/api?weather=pusan", imgPusan, lblPusanCondition, lblPusanTempf, lblPusanTempc, lblPusanHumidity, lblPusanWind);
}
GetWeatherData() 메소드에서는 HttpWebRequest 클래스와 HttpWebResponse 클래스를 이용하여 날씨에 대한 정보를 받은 후에, XmlDocument에 응답받은 스트림을 넣습니다.
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(String.Format(strCityUrl));
httpReq.UserAgent = Request.ServerVariables["HTTP_USER_AGENT"].ToString();
HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(httpRes.GetResponseStream());
httpRes.Close();
그러면, XmlDocument에는 응답받은 스트림인 Xml 정보가 담기게 됩니다. 그 XmlDocument 중 필요한 부분인 "current_conditions"를 구하기 위해 XmlDocument.SelectSingleNode를 통하여 원하는 XmlNode만을 추려냅니다.
XmlNode xWeatherNode = xmlDoc.SelectSingleNode("xml_api_reply/weather/current_conditions");
그리고, 추려낸 XmlNode가 Null이 아닐 경우에 Xml의 정보는 다음과 같습니다.
<current_conditions>
<condition data="대체로 흐림" />
<temp_f data="84" />
<temp_c data="29" />
<humidity data="습도: 74%" />
<icon data="/images/weather/mostly_cloudy.gif" />
<wind_condition data="바람: SW풍, 19 km/h" />
</current_conditions>
이 때, XmlNode에서 필요한 Node를 SelectSingleNode 메소드를 이용하여 값을 구한 후 각각의 Image 컨트롤과 Label 컨트롤에 할당시킵니다.
if (xWeatherNode != null)
{
imgWeather.ImageUrl = _googleUrl + xWeatherNode.SelectSingleNode("icon").Attributes["data"].Value;
lblCityCondition.Text = xWeatherNode.SelectSingleNode("condition").Attributes["data"].Value;
lblCityTempf.Text = xWeatherNode.SelectSingleNode("temp_f").Attributes["data"].Value;
lblCityTempc.Text = xWeatherNode.SelectSingleNode("temp_c").Attributes["data"].Value;
lblCityHumidity.Text = xWeatherNode.SelectSingleNode("humidity").Attributes["data"].Value;
lblCityWind.Text = ReplaceFromHanToEng(xWeatherNode.SelectSingleNode("wind_condition").Attributes["data"].Value);
}
ReplaceFromHanToEng() 메소드는 구글에서 넘겨주는 데이터가 SW풍, NW풍 과 같이 영문으로 방향을 넘겨주기 때문에 한글로 변환하여 보여지게 하기 위한 메소드입니다.
이제, 웹 브라우저를 실행시키면 서울과 부산의 날씨 정보가 나타나게 됩니다.
그림 2. 서울과 부산의 날씨 정보
어떻습니까? 간단한 코드만으로도 우리는 원하는 국가의 날씨 정보를 화면에 출력할 수 있습니다.
이상으로 구글에서 제공하는 날씨 API를 가지고 화면에 출력하는 방법에 대해서 설명드렸습니다.
만약, 다음과 같이 화면을 출력하려면 어떻게 해야 할까요???
그림 3. 오늘/내일/모레의 날씨
위에서 설명드린 소스를 바탕으로 한번 코드를 작성해 보시기 바랍니다.
감사합니다. ^^;;
포스팅을 마치며... ----------------------------------------------------------------------------
정말 간단하게 도시의 날씨 정보를 화면에 출력할 수가 있네요. 조만간 홈페이지에 붙여야겠습니다. 구글에서 유용한 API들을 많이 제공하는데, 구글에서 제공하는 API들에 대해서 좀 더 깊숙하게 알아보아야 하겠습니다.

이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-동일조건변경허락 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.