Thursday, November 8, 2007

Using the NWS Web Service to get forecast

My wife, as many of you know, works for the National Weather Service here in Riverton. So when it came time to redesign our company's website, I decided that I was going to show the forecast from them using their Web Service. For the most part this is a very simple task, except for one small modification that has to be done to the Reference.vb File.

So First of all, Create a Web Application.

Verify that the following Assemblies are included:
  • System.Web.Services
  • System.XML
Right click on the References folder, and click "Add Web Reference"

Enter the URL: http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl

Now normally, you can simply start using the WebService at this point. However, for this one, you need to do some custom editing the Reference Map associated with the Web Service. Under the Project menu, click the button for Show All Files.

Then navigate to the Reference.vb file.


Add the following method after the existing New() Routine:

Protected Overrides Function GetWebRequest(ByVal uri AsUri) As
System.Net.WebRequest

Dim webRequest As System.Net.HttpWebRequest =
MyBase
.GetWebRequest(uri)

webRequest.KeepAlive =

False


Return
webRequest

End Function

Ok now, it is time to edit
the WebForm1.aspx.vb file. For simplicity sake, import the following items:


Imports System.Xml


Imports System.Xml.Xsl


Imports System.Text


Imports System.Configuration


Imports System.IO



Optionally you may also imports the gov.weather.www Namespace.

Now, Lets declare the variables we're going to use.


Dim ndfdXML As New
gov.weather.www.ndfdXML


Dim result As
String


Ok, phew that was easy. Now to retrieve the forecast information, we will use the NDFDgenByDay function which uses the following parameters:



latitude As Decimal


longitude As Decimal

startDate As Date

numDays As String

format As gov.weather.www.formatType

For my case, I'm going to give you the forecast for Riverton, Wyoming, for the next 3 days. So the code will appear as such.


result = ndfdXML.NDFDgenByDay(43.1806, -108.926, Now, 3, gov.weather.www.formatType.Item12hourly)

From here, you can do as you wish to display the data you are looking for. Shortly, I will add a new post that explains how to take this data, then using XSL, transform it into reader friendly HTML Code complete with the NWS images displayed for weather conditions.