GET POSTAL CODE BY USING GOOGLE GEOCODE MAPS API IN VB.NET

During working with one of my desktop application.

I had to implement how to get the exact PostalCode with respect to the Address values supplied, as there are more than one PostalCode exists for a combination of City and StateProvidence for USA country may be for others also. After looking into and trying for getting this done i found a nice feature of using google maps API.

By which i can get the exact postalcode for any address supplied(address1, city, stateprovidence).

Here is an code example with proper comments to implement this:-

Public Function GetZipcode(ByVal address1 As String, ByVal city As String, _
ByVal state As String) As String
 
Dim addressxml As String = String.Empty
Dim zipCode As String = String.Empty
 
Try
 
'Create an object of web client
Dim wsClient As New WebClient()

'Construct the URL concating the address values with it
Dim zipcodeurl As String = "?address={0},+{1},+{2}&sensor=false"
'Here in constructing the URL sensor(is required) indicates whether or not the geocoding request comes from a device with a location sensor.

Dim url As String = "http://maps.googleapis.com/maps/api/geocode/xml" & zipcodeurl
url = [String].Format(url, address1.Replace(" ", "+"), city.Replace(" ", "+"), state.Replace(" ", "+"))

'Download the data in XML format as string by making a web request
addressxml = wsClient.DownloadString(url)
 
'Check if status is OK then proceed
If addressxml.Contains("OK") Then
 
'Check if postal_code section is there in the string then proceed
If addressxml.Contains("postal_code") Then
Dim xmlDoc As New XmlDocument()
xmlDoc.LoadXml(addressxml)
Dim m_nodelist As XmlNodeList
 
'Get the list of all address_companent nodes as this component only contans the address information
m_nodelist = xmlDoc.SelectNodes("/GeocodeResponse/result/address_component")

'From each component check for the type section for getting the particular postal_code section
For Each m_node In m_nodelist
'Get the zipLongName Element Value
Dim zipLongName = m_node.ChildNodes.Item(0).InnerText
'Get the zipShortName Element Value
Dim zipShortName = m_node.ChildNodes.Item(1).InnerText
'Get the zipType Element Value
Dim zipType = m_node.ChildNodes.Item(2).InnerText
 
'If the type of the component is postal_code then get the postal code as zipLongName
If zipType = "postal_code" Then
zipCode = zipLongName
End If
Next

 
End If
 
End If

 
Catch ex As WebException

ErrorLog.WriteErrorLog(ex, "GetZipcode", "CompanyDetailViewerForm")

 
End Try

Return zipCode

 
End Function

Go through the below link for details of using Google Maps API. Reference:-

http://code.google.com/apis/maps/documentation/geocoding/#StatusCodes

150 150 Burnignorance | Where Minds Meet And Sparks Fly!