Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#
Article

Geocoding a Physical Address using Yahoo Web Services and C#

Rate me:
Please Sign up or sign in to vote.
4.08/5 (6 votes)
21 Jan 2008CPOL3 min read 39.6K   428   33   1
An article on geocoding a physical address using Yahoo Web Services and C#
Image 1

Introduction

Yahoo Web Services are made available to developers through Yahoo’s Developer Network; a variety of services are available but this article is specifically interested in using Yahoo’s Geocoding Service. This service will return the closest matching address to a submitted physical address and will also return the address' position in latitude and longitude. The terms and conditions for using the service are pretty simple; users are permitted to geocode up to 5,000 addresses per day for the very reasonable price of absolutely nothing.

This article will demonstrate the basics of submitting an address to the service, recovering and displaying the geocoded result, and will also demonstrate a simple approach to displaying the location as mapped using Yahoo maps. For more information regarding the program, refer directly to the Yahoo Developer Network website located here.

On a limited basis, the service can be used to obtain and store latitude and longitude on all of the addresses contained in some sort of contact database or asset location database, or might be useful for storing waypoints in a GPS device. Naturally the service is based upon physical addresses so its use is limited to tagging physical addresses with a lat/long.

When visiting the site, take a look at the different programs available and take a look at some of the many services made available through Yahoo.

Image 2

Figure 1: The demonstration application running.

Image 3
Figure 2: Displaying the coordinates in Yahoo Maps.

Getting Started

In order to get started, unzip the included project and open the solution in the Visual Studio 2005 environment. In the solution explorer, you should note these files:

Image 4

Figure 3: Solution Explorer.

The Main Form (Form1.cs)

The main form is the only form contained in the application; all of the application specific code required to access the service, return the results of an address search, and to display those results as text or as a map are included in this class.

The code is pretty simple, if you'd care to open the code view up in the IDE, you will see that the code file begins as follows:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

The imports are primarily per the default configuration for a Windows application; the System.Xml library import is the only departure from the default.

Following the imports, the namespace and class are defined and a default constructor added.

C#
namespace YahooGeocoding
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }

Next up is the declaration of a structure used to contain the results returned from a request to geocode a physical address.

C#
/// <summary>
/// Address Struct is used to contain
/// the elements of the geocoded address
/// returned from the Yahoo Map Service
/// </summary>
public struct Address
{
    public string Street;
    public string City;
    public string State;
    public string Zip;
    public string Country;
    public string Lat;
    public string Long;
}

// declare an address
Address SearchAddress;

The next section of the code is used to request a search on an address; this request is submitted to Yahoo’s service which returns the nearest matching address along with its latitude and longitude. The geocoded address returned from the service is stored in an Address.

C#
/// <summary>
/// Call the Yahoo map service to geocode an address and return
/// that address to the caller
/// </summary>
/// <param name="street"></param>
/// <param name="city"></param>
/// <param name="state"></param>
/// <returns>A geocoded address</returns>
private Address GetAddress(string street, string city, string state)
{
    Address newAddress = new Address();
    // Get XML document 
    XmlTextReader reader =
        new XmlTextReader("http://local.yahooapis.com/
        MapsService/V1/geocode?appid=YahooDemo&street=" + 
        street + "&city=" + city + "&state=" + state);
    // Whitespace 
    reader.WhitespaceHandling = WhitespaceHandling.Significant;
    // Report Node Values 
    while (reader.Read())
    {
        if (reader.Name.ToString() == "Address")
            newAddress.Street = reader.ReadString().ToString();
        if (reader.Name.ToString() == "City")
            newAddress.City = reader.ReadString().ToString();
        if (reader.Name.ToString() == "State")
            newAddress.State = reader.ReadString().ToString();
        if (reader.Name.ToString() == "Zip")
            newAddress.Zip = reader.ReadString().ToString();
        if (reader.Name.ToString() == "Country")
            newAddress.Country = reader.ReadString().ToString();
        if (reader.Name.ToString() == "Latitude")
            newAddress.Lat = reader.ReadString().ToString();
        if (reader.Name.ToString() == "Longitude")
            newAddress.Long = reader.ReadString().ToString();
    }
    return newAddress;
}

The find button click event handler starts a search for the user supplied address; the nearest match is displayed on the form’s search results.

C#
/// <summary>
/// Initiate a search for an address using the yahoo service; return
/// the geocoded results into an a new Address and then display
/// the values contained on that address using the textboxes
/// in the result section of the main form.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnFind_Click(object sender, EventArgs e)
{
    if (txtSearchCity.Text == string.Empty ||
    txtSearchState.Text == string.Empty ||
    txtSearchStreet.Text == string.Empty)
    {
        MessageBox.Show("Complete all search terms prior to 
        submitting a request.", 
        "Invalid Request");
        return;
    }
    // setup a new address
    SearchAddress = new Address();
    try
    {
        // populate the address 
        SearchAddress = GetAddress(txtSearchStreet.Text, 
        txtSearchCity.Text, 
        txtSearchState.Text);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message, "Error");
    }
    // clear out the text from all of the result textboxes
    CleanTextboxes();
    // load the search results into the textboxes
    try
    {
        txtStreet.Text = SearchAddress.Street;
        txtCity.Text = SearchAddress.City;
        txtState.Text = SearchAddress.State;
        txtZip.Text = SearchAddress.Zip;
        txtCountry.Text = SearchAddress.Country;
        txtLatitude.Text = SearchAddress.Lat;
        txtLongitude.Text = SearchAddress.Long;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message, "Error");
    }
}

The next bit of code is used to clear out all of the search results section text boxes.

C#
/// <summary>
/// Clear out all of the text in the results
/// section of the form 
/// </summary>
private void CleanTextboxes()
{
    txtStreet.Text = string.Empty;
    txtCity.Text = string.Empty;
    txtState.Text = string.Empty;
    txtZip.Text = string.Empty;
    txtCountry.Text = string.Empty;
    txtLatitude.Text = string.Empty;
    txtLongitude.Text = string.Empty;
}

The next event handler exits the application if the user decides to shut down the program.

C#
/// <summary>
/// Exit the application
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
    Application.Exit();
}

The last bit of code contained in the application is used to open the Geocoded coordinates returned from the service into a running instance of Yahoo Maps. The approach here is simply to format a query string using the values returned from the service.

C#
/// <summary>
/// Map the location
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMapLocation_Click(object sender, EventArgs e)
{
    try
    {
        MessageBox.Show("Mapping Address: " + 
            SearchAddress.Street.ToString(), 
            "Mapping Location");
    }
    catch
    {
        MessageBox.Show("Invalid address", "Error");
        return;
    }
    System.Diagnostics.Process.Start("iexplore.exe", 
        "http://maps.yahoo.com/#mvt=m&lat=" + SearchAddress.Lat +
        "&lon=" + SearchAddress.Long + "&mag=3&q1=" + 
        SearchAddress.Lat + "%2C%20" + SearchAddress.Long);
}

Summary

This application was provided as an example of how one might take advantage of the Yahoo Address Geocoding service. This service, along with many others provided by Yahoo, is available at no cost to the developer. If one were required to geocode a collection of addresses, yet lacked access to some of the available third party tools (such as the ESRI product line), this service could be invaluable. The service mentioned in this article is only a small part of the overall offering and I would encourage anyone interested in providing a low cost, Web based mapping solution to investigate the Yahoo Developer’s Network.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGood One. Pin
viv281221-Aug-08 11:36
viv281221-Aug-08 11:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.