Saturday, May 4, 2013

Google Weather

This weather function can be created a few different ways. I created labels and plugged in the values. You can also, put this into a method or place it in your Page_Load. Have Fun!!
HttpWebRequest  theGoogleRequest  = null;   
HttpWebResponse theGoogleResponse = null;   
XmlDocument     theGoogleXMLdoc   = null;   
StringBuilder   theStringBuilder  = new StringBuilder();   

try{   
theGoogleRequest  = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api?weather="
+ "Lenexa, KS");   
  
theGoogleResponse = (HttpWebResponse)theGoogleRequest.GetResponse();
theGoogleXMLdoc   = new XmlDocument();
  
theGoogleXMLdoc.Load(theGoogleResponse.GetResponseStream());
  
XmlNode root = theGoogleXMLdoc.DocumentElement;
XmlNodeList nodeList  = root.SelectNodes("weather/current_conditions");
XmlNodeList nodeList1 = root.SelectNodes("weather/forecast_conditions");
  
current_temp.Text = nodeList.Item(0).SelectSingleNode("temp_f").Attributes["data"].InnerText;   
hi_temp.Text = nodeList1.Item(0).SelectSingleNode("high").Attributes["data"].InnerText;   
lo_temp.Text = nodeList1.Item(0).SelectSingleNode("low").Attributes["data"].InnerText;   
condition_icon.Text = "< img src=" + "'" + "http://google.com" +
nodeList.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText + "'" + "  alt='' /> ";
condition.Text = nodeList.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText;   
  
string theWindSpeed = nodeList.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerXml;   
  
Match theMatch = Regex.Match(theWindSpeed, "(?:\\d+)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (theMatch.Success)
{   
 condition_wind.Text = theMatch.Value;   
}               
}   
catch (System.Exception ex)   
{   
 ErrorHelper.LogError("weather:Page_Load", ex);   
}   
finally   
{   
 theGoogleResponse.Close();   
}  

No comments:

Post a Comment