Click here to Skip to main content
15,869,940 members
Articles / Web Development / HTML
Article

GeoLocation using REST, AJAX, and Yahoo! for use with Google Maps

Rate me:
Please Sign up or sign in to vote.
4.43/5 (11 votes)
24 Oct 20063 min read 120.6K   886   66   16
Implementing geolocation using REST, AJAX and Yahoo! for use with Google Maps.

Sample Image

Introduction

This was a project I did to explore the Google Maps API. Google Maps is a great JavaScript driven service, and extremely easy to use and manipulate (Great job, Google). But, it has a severe limitation, it does not have a source of geo-location information accessible via the API.

For example, if I want to display my address on a Google Map, I need to know the latitude and longitude so I can set the point via the API. This presented a problem as I have no idea what that would be, and in a real world application, if I wanted to plot some data points, I would need a way figure that out.

Yahoo! to the rescue! Yahoo! has a very cool (and free) Web Service for GeoCoding. However, the trick is to make Yahoo!'s service play nice with Google Maps. The answer was obvious, I needed to use AJAX and a custom class to query Yahoo!'s information directly and transfer it to the JavaScript.

Geocode Class Internals

The Geocode class I wrote to query Yahoo!'s Web Service is very simple. All I had to do was construct the URL according to the specifications defined by Yahoo!, and point an XmlDocument to that URL. Next, I parse the data using xPath statements to a Hashtable. (I'm not an XML guru, there is most likely a better way to write these xPath queries.)

VB
Private Function Query
    Dim XmlDoc as new XmlDocument
    Dim XmlNS  as new XmlNamespaceManager(xmlDoc.NameTable)

    Try
       XmlDoc.Load(BuildURL)
       XmlNS.AddNamespace("def","urn:yahoo:maps")

       mResults("Latitude")  = _
         XmlDoc.SelectSingleNode(".//def:Latitude", XmlNS).InnerXML
       mResults("Longitude") = _
         XmlDoc.SelectSingleNode(".//def:Longitude", XmlNS).InnerXML
       mResults("Address")   = _
         XmlDoc.SelectSingleNode(".//def:Address", XmlNS).InnerXML
       mResults("City")      = _
         XmlDoc.SelectSingleNode(".//def:City", XmlNS).InnerXML
       mResults("State")     = _
         XmlDoc.SelectSingleNode(".//def:State", XmlNS).InnerXML
       mResults("Zip")       = _
         XmlDoc.SelectSingleNode(".//def:Zip", XmlNS).InnerXML
       mResults("Country")   = _
         XmlDoc.SelectSingleNode(".//def:Country", XmlNS).InnerXML
   Catch e as Exception
       Return False
   End Try

   Return True
End Function

Note: For full details, please see the source code, and for information on how I constructed the URLs, refer to my URLBuilder class (included in the source).

GeoCoder Class In Action

To query Yahoo!'s Web Service, all you need to do is create the object and pass it two parameters:

VB
Dim myGeocode as New Clarity.Utils.Geocode("AppID", "Free Form Text")

Alternately, you can also pass them in like this:

VB
Dim myGeocode as New Clarity.Utils.Geocode("AppID")

myGeocode.Street   = ""
myGeocode.City     = ""
myGeocode.State    = ""
myGeocode.Zip      = ""
myGeocode.Location = ""

Now, to read the data sent back from the query is extremely easy. Just execute the Results function passing in the corresponding values.

VB
'*****************************************
' Here are the possible values:
'*****************************************
' Clarity.Utils.Geocode.ResultType.Latitude
' Clarity.Utils.Geocode.ResultType.Longitude
' Clarity.Utils.Geocode.ResultType.Address
' Clarity.Utils.Geocode.ResultType.City
' Clarity.Utils.Geocode.ResultType.State
' Clarity.Utils.Geocode.ResultType.Zip
' Clarity.Utils.Geocode.ResultType.Country
'
Console.WriteLine(" Latitude: " & _
  myGeocode.Results(Clarity.Utils.Geocode.ResultType.Latitude))
Console.WriteLine("Longitude: " & _
  myGeocode.Results(Clarity.Utils.Geocode.ResultType.Longitude))

Geocode Class Testing Application

Not much to explain with this, I just needed a way to test the GeoCode class, so I wrote a quick console app.

VB
Sub Main()
     Dim Location as String

     Console.WriteLine(".NET Interface" & _ 
          " for Yahoo's GeoLocation Web-Service")
     Console.WriteLine("Matthew Hazlett, Clarity Computers")
     Console.WriteLine()

     Console.Write("Enter address: ")
     Location = Console.ReadLine
     Console.WriteLine()

     Dim myGeocode as New Clarity.Utils.Geocode("AppID", Location)

     Console.WriteLine("  Address: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.Address))
     Console.WriteLine("     City: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.City))
     Console.WriteLine("    State: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.State))
     Console.WriteLine("      Zip: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.Zip))
     Console.WriteLine("  Country: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.Country))
     Console.WriteLine()
     Console.WriteLine(" Latitude: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.Latitude))
     Console.WriteLine("Longitude: " & _
       myGeocode.Results(Clarity.Utils.Geocode.ResultType.Longitude))
     Console.WriteLine()

     Console.Write("...Slam Return...")
     Console.Read
End Sub

AJAX vs. Mr. Clean

If you don't know what AJAX is then you can refer to the plethora of information on the web. [Definition, AJAX Library for .NET]

I'm not going to go into how to add AJAX to your project or how to create an AJAX page. You will need to refer to the Quick Start documentation for that information. I have also not included the Google Mapping functions, this is just a sample application of how to query Yahoo! with AJAX (but they are included in the source).

The following is the code used by the web application to accomplish the GeoCode functions:

VB
Protected Sub Page_Load(ByVal sender As Object, _
           ByVal e AsSystem.EventArgs) Handles Me.Load
    Ajax.Utility.RegisterTypeForAjax(GetType(_Default))
End Sub

<Ajax.AjaxMethod()> _
Public Function Lookup(Location as String) as ArrayList
    Dim Geo as new Clarity.Utils.Geocode("AppID", Location)
    Dim Results as New ArrayList
    
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.Latitude))
    
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.Longitude))
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.Address))
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.City))
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.State))
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.Zip))
    Results.Add(Geo.Results(Clarity.Utils.Geocode.ResultType.Country))
    
    Return Results
End Function

The Lookup function looks like a normal function but it's really an AJAX function. This means we can call this function from the JavaScript contained in the page (pretty neat). Finally, here is the JavaScript used on the page to invoke the Lookup function.

Notice the function is called like this: Result = Class.Function(args);.

JavaScript
function MapMe() {
    text    = document.getElementById("Location").value;
    LocData = _Default.Lookup(text);
    
    document.getElementById("Latitude").innerHTML  = LocData.value[1];
    document.getElementById("Longitude").innerHTML = LocData.value[0];
    document.getElementById("Address").innerHTML   = LocData.value[2];
    document.getElementById("City").innerHTML      = LocData.value[3];
    document.getElementById("State").innerHTML     = LocData.value[4];
    document.getElementById("Zip").innerHTML       = LocData.value[5];
    document.getElementById("Country").innerHTML   = LocData.value[6];
}

Finally!

Well, this wasn't the most complicated project but definitely one of the most fun! I wanted to share my work and hope someone else will find it useful and create the next great HousingMaps.Com (not mine, just a cool Map Hack).

Post up the links to your Google Map Hacks!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I started programming for fun when I was about 10 on an Franklin Ace 1000.

I still do it just for fun but it has gotten me a few jobs over the years. More then I can say for my Microsoft Certifications. Smile | :)

The way I learned was by example, now its time to give back to the next generation of coders.



Comments and Discussions

 
GeneralUpdate Pin
Matthew Hazlett9-Feb-10 7:34
Matthew Hazlett9-Feb-10 7:34 
QuestionGeoLocation adapted for ASP.NET solution? Pin
sbx141-May-07 8:52
sbx141-May-07 8:52 
AnswerRe: GeoLocation adapted for ASP.NET solution? Pin
tanweer11-Aug-10 22:29
tanweer11-Aug-10 22:29 
Hi try This
it is very simple:

Dim ipAddress As String = something
Dim req As WebRequest = WebRequest.Create("http://ipinfodb.com/ip_query.php?ip=" & ipAddress)
Dim resp As WebResponse = req.GetResponse()
Dim s As Stream = resp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(s, Encoding.ASCII)
Dim doc As String = sr.ReadToEnd() ' get text to a string
Dim length As Integer = doc.Length - 1
Dim startInd As Integer = doc.IndexOf("<CountryCode>") + 13
doc = doc.Substring(startInd)
length = doc.Length - 1
Dim tagStart As Integer = doc.IndexOf("<")
Dim code As String = doc.Remove(tagStart, length - tagStart)
startInd = doc.IndexOf("<CountryName>") + 13
doc = doc.Substring(startInd)
length = doc.Length - 1
tagStart = doc.IndexOf("<")
Dim Country As String = doc.Remove(tagStart, length - tagStart)
startInd = doc.IndexOf("<RegionName>") + 12
doc = doc.Substring(startInd)
length = doc.Length - 1
tagStart = doc.IndexOf("<")
Dim RegionName As String = doc.Remove(tagStart, length - tagStart)
startInd = doc.IndexOf("<City>") + 6
doc = doc.Substring(startInd)
length = doc.Length - 1
tagStart = doc.IndexOf("<")
Dim City As String = doc.Remove(tagStart, length - tagStart)
startInd = doc.IndexOf("<ZipPostalCode>") + 15
doc = doc.Substring(startInd)
length = doc.Length - 1
tagStart = doc.IndexOf("<")
Dim ZipCode As String = doc.Remove(tagStart, length - tagStart)
startInd = doc.IndexOf("<Latitude>") + 10
doc = doc.Substring(startInd)
length = doc.Length - 1
tagStart = doc.IndexOf("<")
Dim Latitude As String = doc.Remove(tagStart, length - tagStart)
startInd = doc.IndexOf("<Longitude>") + 11
doc = doc.Substring(startInd)
length = doc.Length - 1
tagStart = doc.IndexOf("<")
Dim Longitude As String = doc.Remove(tagStart, length - tagStart)
''
'put values on the page
lblCity.Text = City
lblCountry.Text = Country
lblCountryCode.Text = code
lblZip.Text = ZipCode
lblRegion.Text = RegionName
lblLat.Text = Latitude
lblLong.Text = Longitude
QuestionHow to get Google Maps API Pin
Lord_Chiru6-Jan-07 16:43
Lord_Chiru6-Jan-07 16:43 
GeneralAlternative method (purchase data) Pin
Steven Berkovitz24-Oct-06 6:43
Steven Berkovitz24-Oct-06 6:43 
GeneralI say free is a better price... Pin
Eli.M1-Nov-06 6:37
Eli.M1-Nov-06 6:37 
GeneralVisual Studio 2003 Version Pin
djvoracious4-May-06 15:51
djvoracious4-May-06 15:51 
GeneralPort this to pageflakes.com Pin
Omar Al Zabir2-Jan-06 16:29
Omar Al Zabir2-Jan-06 16:29 
GeneralRe: Port this to pageflakes.com Pin
Matthew Hazlett2-Jan-06 16:34
Matthew Hazlett2-Jan-06 16:34 
GeneralTitle Pin
Brad Bruce22-Dec-05 4:16
Brad Bruce22-Dec-05 4:16 
GeneralLive Demo Pin
Matthew Hazlett21-Dec-05 10:34
Matthew Hazlett21-Dec-05 10:34 
JokeRe: Live Demo Pin
Smitha Nishant21-Dec-05 10:41
protectorSmitha Nishant21-Dec-05 10:41 
GeneralRe: Live Demo Pin
Matthew Hazlett21-Dec-05 10:46
Matthew Hazlett21-Dec-05 10:46 
GeneralRe: Live Demo Pin
Phebous27-Dec-05 9:30
Phebous27-Dec-05 9:30 
GeneralRe: Live Demo Pin
Jafin23-Oct-06 18:21
Jafin23-Oct-06 18:21 
GeneralRe: Live Demo Pin
Matthew Hazlett23-Oct-06 18:29
Matthew Hazlett23-Oct-06 18:29 

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.