Fetch Weather Data from Google Server on VB

google weather api

Here’s a code for fetching weather data from Google server through its undocumented weather Application Programming Interface (API) which was developed for use with iGoogle. The code below is part of the Flight Information Display System (FIDS) I’ve developed for some airline company few years ago.


Attribute VB_Name = "weatherData"
Dim xmlWeather As MSXML2.XMLHTTP60
Dim xmlWeatherResult As String
Dim xmlWeatherData As MSXML2.DOMDocument60
Dim xmlWeatherDataElement As MSXML2.IXMLDOMElement
Dim weatherCondition As String
Dim weatherTempC As String
Dim weatherTempF As String
Public destWeatherData As String

Public Function getWeatherData(wLocation As String)
    On Error Resume Next

    Set xmlWeather = New MSXML2.XMLHTTP60
        xmlWeather.open "GET", "http://www.google.com/ig/api?weather=" & Replace(wLocation, " ", "%20") & "&hl=en", False
        xmlWeather.send
        xmlWeatherResult = xmlWeather.responseXML.xml

    If InStr(1, xmlWeatherResult, "temp_c", vbTextCompare) > 0 Then
        Set xmlWeatherData = New MSXML2.DOMDocument60
        xmlWeatherData.loadXML (xmlWeatherResult)

        Set xmlWeatherDataElement = xmlWeatherData.selectSingleNode("//condition")
            weatherCondition = xmlWeatherDataElement.getAttribute("data")

        Set xmlWeatherDataElement = xmlWeatherData.selectSingleNode("//temp_c")
            weatherTempC = xmlWeatherDataElement.getAttribute("data")

        Set xmlWeatherDataElement = xmlWeatherData.selectSingleNode("//temp_f")
            weatherTempF = xmlWeatherDataElement.getAttribute("data")

        If weatherTempC <> "" And weatherTempF <> "" Then
            destWeatherData = weatherTempC & "C / " & weatherTempF & "F"
        End If
    End If
End Function

This part of the code goes to your form.


Private Sub cmdFetchWeather_Click()
    If comboNewDestination.Text <> "" Then
        getWeatherData (comboNewDestination.Text & ",Philippines")

        If destWeatherData <> "" Then
            txtNewWeather.Text = destWeatherData
            destWeatherData = ""
        Else
            MsgBox "Weather data not available, Please try again later!", vbOKOnly + vbCritical, "Error Fetching Weather Data"
            txtNewWeather.Text = ""
        End If

    End If
End Sub

I’ll probably find more goodies from my old cranky drive so stay tune as I intend to post everything I’ll find useful there.


Permalink • Print • Comment

Trackback uri

http://seoroot.com/blog/tips-and-howtos/fetch-weather-data-from-google-server.html/trackback

Related Entries

1 Comment on Fetch Weather Data from Google Server on VB »

Scott @ 3:06 pm:

What type of reference should be set? I get an error on the MSXML2 elements and I don’t know which reference your have set.

Leave a Comment