Provided By Certified Computer Experts, Inc.
main title
Quality information to help the SEO community - money and time saving tips - straight from the experts!

Mapping Points Using Google's Map API - Part 1

In this tutorial I wanted to go over how to take raw data from just about any source and then plot the points on a Google map. This process can be done in any number of ways, I know myself I have done a little differently each time - mainly due to constraints or a customers request. In this particular request I had very limited time. I was asked to take data from their client management system and then place it on a Google map. Let's see how we should start such a process.

Planning

Yes that's right, even if you don't do much of it you have to start with some sort of planning. Lack of doing so will no doubt cause you trouble down the road. In this case I already had the data exported into CSV format. I know from there somehow we must geocode (convert the addresses into mapable latitude / longitude coordinates). First things first, I put my CSV into Excel then into an Access (Yea I know) database. So now what? Well once we have our data we must then geocode the addresses then plot them on a map. In this case I used a PHP file to output all my addresses in XML. The JavaScript calls that using GDownloadURL then geocodes each address and outputs it to the browser. Then you just have to save that in a file for your map program to plot it. In my particular case I already had another JavaScript page already written that could accept an XML file and plot the points so I used that. I really should have just one JavaScript app to both request the data, geocode then display the points on the map. I just didn't have the time to do all that. I suppose the right way would have PHP comunicate with JavaScript by having JavaScript query PHP for all addresses. Once each one is geocoded send it back to PHP using XML or JSON. PHP would then write the latitude longitude to the database. Next time the script is ran JavaScript would query PHP and this time find all the addresses geocoded and just skip that step and plot them. Anyway in my example we are just mass geocoding.

What is the best way to geocode a bunch of addresses?

You'll note that I decided to loop over using the GClientGeocoder class. However lets take a note from Google's reference page about that class.

This class is used to communicate directly with Google servers to obtain geocodes for user specified addresses. In addition, a geocoder maintains its own cache of addresses, which allows repeated queries to be answered without a round trip to the server. As a general best practice, it is not recommended to use GClientGeocoder functions in a loop. Developers that have multiple addresses to geocode should probably use our HTTP Geocoder instead.

Google says in not recommended to use this class to loop over? There are limits on both the JavaScript class and the HTTP geocoder. Its true that the HTTP geocoder has less strict limits. In my particular case I needed 2000 addresses geocoded. Simply put using HTTP just wasn't an option because PHP and my web server would both time out. Yes, I increased the timeout on both however I still get the error because I use a custom http wrapper. So in my experience the JavaScript class is faster so that's what we'll use in this tutorial.

So we are using XML data to feed into the following JavaScript file. If your source is CSV you would simply change into XML format. Here is what my XML looks like - view XML source data.

View finished file

Here is our source. I'll heavily comment it so you can get a good understand on what everything does.

// nextAddress function is called once Google is loaded and ready to go
// that'll get everything started
<body onunload="GUnload()" onload="nextAddress()">
// Outputs basic XML header    
<div id="message">&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />&lt;markers&gt;<br /></div>

<script type="text/javascript">
// delay between geocode requests 100 miliseconds seems to work well
// this is used because if you make too many geocodes too often Google
// will throw an error. You also have a daily limit on geocodes as well

var delay = 100;
// checks is browser is compatible - note: isn't it nice how Google does
// this for us? In the past a special function would have to
//check for the browser etc,etc it was such a pain. Google has another nice // function that we'll get to  very soon

if (GBrowserIsCompatible()) {
// Creates an instance of the GClientGeocoder class
      var geo = new GClientGeocoder();
// Geocode function getAddress is defined - it takes an address and a
//
callback function as a argument
      function getAddress(search, next) {
// uses GClientGeocoder method getLocations to search for the given
// address then immediate defines the callback with the result given

        geo.getLocations(search, function (result)
          {
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
// Here we retrieve the values from the result that is in JSON format, for
// a clear idea on what the output looks like take a look at this page
// http://code.google.com/apis/maps/documentation
// services.html#Geocoding_Structured

              var p = result.Placemark[0].Point.coordinates;
              var lat=p[1];
              var lng=p[0];
// Outputs in XML
              var xml = '&nbsp;&nbsp;&lt;marker address="'
 + search + '" lat="' +lat+ '" lng="' +lng+ '"&gt;<br>';
// outputs the xml in our <div>
              document.getElementById("message").innerHTML += xml;
            }
            else {
// If we got here then we got some sort of error. If the error means
// we are requesting too fast then lets increase the delay and try again

              if (result.Status.code == G_GEO_TOO_MANY_QUERIES) {
                nextAddress--;
                delay++;
              } else {
// it wasnt because of a delay so just output the error
                var reason="Code "+result.Status.code;
                var xml = '&nbsp;&nbsp;&lt;marker address="'
+ search + '" error="' +reason+ '"&gt;<br>';
                document.getElementById("message").innerHTML += xml;
              }   
            }
//runs our callback function nextAddress
            next();
          }
        );
      }
// Here we use another great time saving Google function
// GDownloadUrl is just like XmlHttpRequest but does not require
// readState checking - very nice! The file we want to open is passed
// we then say we want the results to follow and passed as doc variable

// note: this is a global variable because its called with var
var addresses = new Array();
GDownloadUrl("listClientsXML.php", function(doc,responseCode) {
// GXml is a XML parser. We take our results and place it into a instance
// of the GXml class

if(responseCode == 200) {
        var xmlDoc = GXml.parse(doc);
// The data we are viewing looks like this from our PHP script
// <client address="3524 ROCKDALE CT,21244">

// gets all the elements named 'client'
var markers = xmlDoc.documentElement.getElementsByTagName("client");
// for until we get to the end of the client elements
        for (var i = 0; i < markers.length; i++) {
// now lets get the address attributes from each one
        var address = markers[i].getAttribute("address");
// add it to our array
        addresses[i] = address;
// the continue
        }   
// Ok now we actually call nextAddress for the first time, we call it
// here because now our XML is done and loaded

nextAddress();
} else {
alert('Can't open file');
}
});

var nextAddress = 0;

// The function that gets it all started (after the XML)
 function nextAddress() {
// starts one at a time ..
        if (nextAddress < addresses.length) {
//setTimeout creates our delay, then getAddress with first address
// from our address array, pass our callback function (this func) and
// also tell setTimeout our delay then move to next address

      setTimeout('getAddress("'+addresses[nextAddress]+'",nextAddress)', delay);
          nextAddress++;
        } else {
// we're done, close the xml
          document.getElementById("message").innerHTML += "&lt;/markers&gt;";
        }
      }
}
// display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
    </script>

That's it! It also should be noted I got some of this source from http://www.commchurch.freeserve.co.uk the tutorials there are really great and I suggest everyone take a look at them. 

Ok so now we have our JavaScript source. I'm pretty tired now so I'm going to call it a night. Stay tuned and I'll show you the PHP file used for the XML and also the final step - the map program.

Download source file

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Awesome! Very helpful :)
Posted By Keith on 11/29/08 11:53 AM
I read through and setup my own data and got the google javascript geodecoder going but don't know what the next step is.

Are you going to write a part2?

i'm trying to get about 800 points plotted on a google map.

your article has been very helpful so far! :)
Posted By Chris on 1/15/09 4:28 PM
Hey thanks Chris!! I've been a bit busy but its nice to know the article was helpful to you. I'll try and knock it out in the next day or so.
Posted By Tom on 1/15/09 4:32 PM
Ok I recently updated the source file so it actually works. Again the source file really just pulls from listClientsXML.php. listClientsXML.php is just a php script that pulls addresses from a database and outputs them in XML format. So really you could replace with listClientsXML.php an XML file and it would work the same.

So now run my source and you will see it uses JavaScript to quickly loop over the geocoding. Next I'll show the map program, its pretty basic so it shouldn't take me too long.
Posted By Tom Fitzgerald on 1/29/09 12:25 AM
I am trying to output a large number of geocoded points, but my browser loops through them too quickly and gives me errors. Even using the timeout I get the same problem. Any ideas?
Posted By Max on 3/11/09 11:47 AM
Topics

Fresh Books Billing
Fresh Books Billing
Fresh Books Billing

  • Subscribe

  • Add to your Google Home Page or Google Reader Add to your My Yahoo!
    Add to your My MSN Add to your My AOL
    Add to your My Feedster Add to your NewsGator
    Add to your Bloglines Add to your News Burst
    Add to your Rojo Add to your Pluck

  • Search Blog
  • Subscribe
  • Enter your email address to subscribe.

Free Computer Advice
  • Recent Posts From FreeComputerAdvice.net

  • Windows 7 - Why I think it has a shot of working

    There's a million blogs talking about how great / bad Windows 7 is. My biggest problem has always not been with Windows 7 but rather with Vista. As an IT professional I'm aware that no business wants Vista. Why? Because [insert proprietary software name] won't run on it. So if it won't run on Vista how does Win...


  • Conflicker Virus - Apparently NOT a hoax

    Well I know I'm a few days behind on this but the Conflicker is most definitily not a hoax. Reports show that the virus has activated and the infected clients are starting to attack others. If you are interested in this topic at all, I'm sure you already read this somewhere else - no use in me just repeating ol...


  • Conflicker virus - hoax or what?

    I've been reading a lot about the conflicker virus that is out there and soon to unleash fury on everyone on Wednesday. This is going to be a really short post but I just want to point out the highlights.

    • This virus has been patched in October in 2008.
    • If your Windows updates are u...

    • Server C Drive Getting Full?

      Many system administrators have had this problem. Your server was preconfigured with only 10GB for the primary parition where Windows is installed. Meanwhile the secondary partition has 36 Terabytes of free space. WTF? Yeah it sucks and of course the admin before you installed Backup exec and virus protection t...


    • Coming Soon(ish)

      Hope everyone is doing ok out there, its been a while since I've had time to make a post. I've been very busy on some exciting projects. I'm getting closer to sharing them with you. Some of the projects fit better on my other blog (the...


    • OMG Gmail is down!!

      If anyone out there is like me, you spend your ENTIRE life in a Gmail web page. Today my life has come to an end. I tried to access my mail at my home office. For some stupid reason the Internet has been flakey for a while now - no luck. I power cycle my Netgear router and cable modem - still no luck. What the ...


    • Turn off Vista's Search Indexing

      It's almost 4am. I can't sleep. Why? Well for one reason all I can hear is my stupid desktop grinding away on the hard drive. I just can't stand this. What is running? I keep my startup items very clean, no un-needed junk! Well maybe I forgot to mention I'm running Vista. Besides user access control asking a st...


    • Make your computer faster

      One of the most commonly questions I get asked is 'How can I make my computer faster?'. Fortunately it's really pretty easy - just remove un-needed startup programs. This video shows you how to do just that and gets into a few other things. You will be amazed by the amount of junk in your startup folder. ...


    • Free Computer Advice - Forums!

      Since this site was started I've had the Ask a question section up and running. Where people can ask tech questions and have them answered. I've always enjoyed how simple the process worked. However I also wanted to have something that was a bit more complex. Enter the forums. Message forums are a lot easier to...


    • Recently Asked Questions

      Check out some of the most recently asked questions in our Ask A Question section.

      Monitor not working
      Here we have a question about someone that cannot get their monitor to work. One day it worked...


    • Google's FriendConnect Today I added the Google FriendConnect application to the site. I think it'll be a fun way for visitors to interact and ask computer questions. I urge you to join and check it out, I'll also be going over how to create applications for Google's FriendConnect in the future. ...

    • Mass Geocoding

      I just wrote a cool tutorial on how to mass geocode addresses using Google's API and JavaScript. Take a look - it was a lot of work for me.

      Mass geocoding

      ...

    • Photoshop Tutorial - Replace a Color on a Car

      Today we'll talk about a quick easy Photoshop tutorial. This is a very simple tutorial that goes over how to change the color of a car. We'll be using the color replace tool and the paint brush tool. [More] ...


    • Recently Asked Questions - Part 2

      XPRT5.DLL / XPRT6.DLL
      Many people have had an issue with this file and America Online. I have understood that downloading the ACS software will fix this issue. If you are having this problem and it has no...


    • Ask A Question - Recent Questions

      Just wanted to share some recently asked questions in our 'Ask A Question' section. If you have a question of your own, feel free to ask it. If you are a techie you are welcome to help answer questions asked by others.

 
Designed & Hosted By Certified Computer Experts, Inc. - Law Firm Web Site Design - OptiLaw
All information on FreeComputerAdvice.net is provided by Certified Computer Experts, Inc.