Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / Javascript
Article

A .NET API for the Google Maps Geocoder

Rate me:
Please Sign up or sign in to vote.
4.38/5 (10 votes)
26 Jun 2008CPOL 134.7K   3.2K   48   25
A simple .NET library to wrap the Google Maps geocoding functionality

Introduction

Google maps allows you to geocode addresses through their JavaScript API or by directly calling http://maps.google.com/maps/geo?output=xml&key=yourkey&q=someaddress for results in XML. Both of these methods can take time to integrate into your .NET code. To make life a little simpler, I've wrapped the functionality of the HTTP geocode request into a .NET library.

Using the Code

You can make a call to only get all XML in a single string:

C#
string xml = GMapGeocoder.Util.GetXml("123 fake street", "your google map key");

You can also get the code back in the original object structure:

C#
string xml = GMapGeocoder.Util.GetXml("123 fake street", "your google map key");
GMapGeocoder.Generated.kml kml = GMapGeocoder.Util.DeserializeXml(xml);
string fullAddress = kml.Response.Placemark[0].address;
string countryCode = kml.Response.Placemark[0].AddressDetails.Country.CountryNameCode;
string stateCode = kml.Response.Placemark[0].AddressDetails.Country.
                AdministrativeArea.AdministrativeAreaName;

For US addresses, the following calls should make more sense than the kml object above:

C#
GMapGeocoder.Containers.Results results = 
    GMapGeocoder.Util.Geocode("123 fake street", "your google map key");
GMapGeocoder.Containers.USAddress match1 = results.Addresses[0];
string city = match1.City;
string state = match1.StateCode;
double lat = match1.Coordinates.Latitude;

Points of Interest

I didn't find an exact XML definition, so I wrote the XSD file based on documentation on Google, along with results I found from making random queries. I included the XSD file just in case this definition is wrong and code needs to be regenerated. I've also noticed that HttpWebRequest.GetResponse() used by the GetXml call is slow on the initial call from an application, but subsequent calls are much quicker.

History

  • 27th May, 2008: Initial post
  • 24th June, 2008: Article updated

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) Cerner
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

 
QuestionThis is useful but Google API has been changed Pin
JoeSchmoe0074-Jun-14 4:25
JoeSchmoe0074-Jun-14 4:25 
QuestionImprovement to PlacemarkPointToPoint Pin
Gregg Lobdell6-Jul-11 12:45
Gregg Lobdell6-Jul-11 12:45 
A small efficiency improvement to the Util method PlacemarkPointToPoint. Use a static for the character to split on array, and only do the split once, instead of three times.

Also remove the inner try block and replace it with a boolean expression to set p.Unbounded. Since this uses Regex to match zero, I suppose you could also use Regex.Split instead of String.Split.

Add to the file header:
using System.Text.RegularExpressions;


Then the changes to the code:
/// <summary>
/// char array used as first argument to Split
/// </summary>
private static char[] splitChar = { ',' };

/// <summary>
/// regex to match for zero
/// </summary>
private static Regex zero = new Regex(@" *0+ *");

/// <summary>
/// Takes point from google containing coordinates in a string and returns point objects with lat/lng separated out.
/// </summary>
/// <param name="point">Google placemark point.</param>
/// <returns>Point containing coordinates. Lat/Lng are set to min double value on parse errors.</returns>
public static Containers.Point PlacemarkPointToPoint(Generated.Point point)
{
    try
    {
        Containers.Point p = new GMapGeocoder.Containers.Point();
        string[] coords = point.coordinates.Split(splitChar);
        p.Longitude = Convert.ToDouble(coords[0]);
        p.Latitude = Convert.ToDouble(coords[1]);
        p.Unbounded = (coords.Length > 2 && !zero.IsMatch(coords[2]));

        return p;
    }
    catch
    {
        return new Containers.Point();
    }
}


If you don't like the Regex match for zero you could use:

int unbound = 0;
p.Unbounded = (coords.Length > 2
               && Int32.TryParse(coords[2], out unbound)
               && unbound != 0);


I like TryParse better because it doesn't throw an error. I view Try/Throw/Catch as a relatively expensive operation, better reserved for truly exceptional situations.

Enjoy!
QuestionUpdate to Google Geocoding V3? Pin
Gregg Lobdell6-Jul-11 8:37
Gregg Lobdell6-Jul-11 8:37 
AnswerRe: Update to Google Geocoding V3? Pin
Member 831154912-Oct-11 20:07
Member 831154912-Oct-11 20:07 
GeneralOnly using aspx.vb Pin
Paul M Gough26-Nov-09 22:06
Paul M Gough26-Nov-09 22:06 
GeneralKML Schema Pin
teggen26-Oct-09 17:13
teggen26-Oct-09 17:13 
GeneralI need complete seach results Pin
sandeepsc12-Sep-09 2:19
sandeepsc12-Sep-09 2:19 
Generalstatus 602 Pin
oksanai25-Jun-09 4:33
oksanai25-Jun-09 4:33 
GeneralProblem with culture/ Utf8 Pin
rouliowiglesias24-Jun-09 16:07
rouliowiglesias24-Jun-09 16:07 
Generalweb project problem Pin
zerointeractive8-Jun-09 12:29
zerointeractive8-Jun-09 12:29 
GeneralVery nice :o) Pin
CipB28-May-09 4:53
CipB28-May-09 4:53 
GeneralRe: Very nice :o) Pin
jonranes28-May-09 7:56
jonranes28-May-09 7:56 
GeneralNice Article Pin
mbaocha6-May-09 11:31
mbaocha6-May-09 11:31 
GeneralMultiple Addresses Pin
BlitzPackage27-Aug-08 9:01
BlitzPackage27-Aug-08 9:01 
GeneralRe: Multiple Addresses Pin
Sharmil Y Desai13-Sep-08 5:29
Sharmil Y Desai13-Sep-08 5:29 
GeneralUK address support Pin
geedubb27-Aug-08 1:08
geedubb27-Aug-08 1:08 
GeneralConnection refused Pin
Lars Karlsson3-Jul-08 21:37
Lars Karlsson3-Jul-08 21:37 
GeneralRe: Connection refused Pin
Sharmil Y Desai7-Jul-08 16:31
Sharmil Y Desai7-Jul-08 16:31 
GeneralRe: Connection refused Pin
Sharmil Y Desai7-Jul-08 16:39
Sharmil Y Desai7-Jul-08 16:39 
GeneralOne more Pin
wjcygan20-Jun-08 6:29
wjcygan20-Jun-08 6:29 
GeneralRe: One more Pin
Sharmil Y Desai24-Jun-08 7:41
Sharmil Y Desai24-Jun-08 7:41 
GeneralSlight change Pin
wjcygan20-Jun-08 4:39
wjcygan20-Jun-08 4:39 
GeneralRe: Slight change Pin
Sharmil Y Desai24-Jun-08 7:38
Sharmil Y Desai24-Jun-08 7:38 
GeneralError Pin
obinna_eke29-May-08 1:24
obinna_eke29-May-08 1:24 
GeneralRe: Error Pin
Sharmil Y Desai29-May-08 10:55
Sharmil Y Desai29-May-08 10:55 

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.