Geocode an address using Google Maps in VB.NET

Introduction

This article addresses a simple approach to using the Google Maps API to geocode a physical address.  To run the code it will be necessary to obtain a key from Google to access and use their API.  The terms and conditions of use and information needed to get started can be found here:  http://code.google.com/apis/maps/

GeocodeAddresses1.jpg
 
Figure 1:  Demonstration Application in Use

The demonstration application provided allows the user to key in a physical street address and to convert that address to a latitude/longitude coordinate pair which can subsequently be used to display the location on a map.
There are limits to the number of free queries that you can execute against the Google Maps API, at that, it might be worth it write a small application to loop through all of your addresses, geocode them one time, and then store the latitude and longitude into a table which your application could use to obtain the coordinates whenever you needed to display that location (for example, if you were displaying a collection of stores, rather than query for the stores each time you need to display them, just do it once and save the values for later use).

Getting Started:
In order to get started, unzip the included project and save it to your hard drive.  There is a single project included in the download.
 
GeocodeAddresses2.jpg
 
Figure 2:  Solution Explorer for the Demo Application

The application project is called "GeocodeAddresses"; it contains a single form (Form1.vb) and a class entitled, "LatLon.vb".  The form is the demonstration whilst the class is used to contain the results of a query to geocode a physical address.

Running the Application
Start the application, key in a valid physical address, and click the "Geocode It" button.  The results will subsequently be displayed in the text box at the bottom of the form.  You can copy those values and paste them into Bing Maps or Google Maps to verify that the location returned is accurate.

GeocodeAddresses3.jpg
 
Figure 3:  Geocode Results verified in Bing Maps

Code:  LatLon.vb

The LatLon class is used merely to contain a latitude/longitude pair returned from the geocoding request.  It contains a pair of doubles:  Latitude and Longitude.  The constructor is overloaded to allow you to set the latitude and longitude upon instantiation of the class if you choose to do so.
Public Class LatLon
    Public Property Latitude As Double
    Public Property Longitude As Double
    Public Sub New()
    End Sub
    Public Sub New(ByVal lat As Double, ByVal lon As Double)
        Me.Latitude = lat
        Me.Longitude = lon
    End Sub
End Class

Code:  Form1.vb
 
The code behind the demo application consists of a single method used to make the geocoding request to Google maps.  There is a single button click event handler that makes the request and displays the results in a text box.  Refer to the documentation provided by Google for more information on the use of this and other methods supplied through the Google Maps API.  The methods are annotated in the following:

Imports System.IO
Imports System.Net
Imports System.Web
Imports System.Collections.Generic
Imports System.ComponentModel
Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles
    MyBase.Load
    End Sub
    ''' <summary>
    ''' Call the GetLatLon method to geocode a physical address
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnGeocode_Click(sender As System.Object, e As System.EventArgs) Handles
    btnGeocode.Click
        Try
            Dim ll As New LatLon()
            ll = GetLatLon(txtAddress.Text)
            txtLatLon.Text = ll.Latitude.ToString() & ", " & ll.Longitude.ToString()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "An error has occurred")
        End Try
    End Sub
    ''' <summary>
    ''' This function makes a call using the Google Maps API to geocode a physical
    ''' address and report the
    ''' latitude and longitude of the address
    '''
    ''' You will need to obtain a Google Maps API key and plug it into the url string the
    ''' space indicated in order for this
    ''' code to execute properly
    '''
    ''' The code could be useful to you if you need to geocode some addresses in order to
    ''' display them on a map, for example if
    ''' your site had a store locator, this code could be used to find the lat/lon of
    ''' each store.  I would recommend obtaining the
    ''' addresses and keeping them in a database table rather than querying Google maps
    ''' for the lat/lon of the address each time it
    ''' is needed.  Google does have limitations upon the number of free queries it will
    ''' support, at that, it might be useful to just
    ''' write an application to loop through all of the addresses, geocode each address,
    ''' and then write those captured lat/lon values
    ''' into your table.
    '''
    ''' Whilst useful, there is nothing particulary interesting about this code; I think
    ''' it is pretty well covered in the Google Maps API documentation
    ''' </summary>
    ''' <param name="addr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetLatLon(ByVal addr As String) As LatLon
        Dim url As String = "http://maps.google.com/maps/geo?output=csv&key=[YOUR KEY
        GOES HERE]&q=" & addr
        Dim request As System.Net.WebRequest = WebRequest.Create(url)
        Dim response As HttpWebResponse = request.GetResponse()
        If response.StatusCode = HttpStatusCode.OK Then
            Dim ms As New System.IO.MemoryStream()
            Dim responseStream As System.IO.Stream = response.GetResponseStream()
            Dim buffer(2048) As Byte
            Dim count As Integer = responseStream.Read(buffer, 0, buffer.Length)
            While count > 0
                ms.Write(buffer, 0, count)
                count = responseStream.Read(buffer, 0, buffer.Length)
            End While
            responseStream.Close()
            ms.Close()
            Dim responseBytes() As Byte = ms.ToArray()
            Dim encoding As New System.Text.ASCIIEncoding()
            Dim coords As String = encoding.GetString(responseBytes)
            Dim parts() As String = coords.Split(",")
            Return New LatLon(Convert.ToDouble(parts(2)), Convert.ToDouble(parts(3)))
        End If
        Return Nothing
    End Function
End Class

Summary

The article addresses a simple approach that may be used to geocode a physical address using the Google Maps geocoding service.  In order to use the service you will need to obtain a key from Google; be sure to read the terms of use before deciding whether or not the service will meet with your requirements.  This and many other useful methods are addressed in the Google Maps API documentation:  http://code.google.com/apis/maps/index.html.

Up Next
    Ebook Download
    View all
    Learn
    View all