Google Maps API Tutorial

Before you go through all the complexities of this tutorial, I recommend that you check out a recent Google Maps development I’ve posted about. I think you’ll find it quite helpful!

In response to a post on the Godbit forum, I created this brief Google Maps API tutorial. I believe every Church website, and every business for that matter, should provide a map and directions. The Google API lets us take that concept to a new level.
After completion of this tutorial you should be able to:

  • Have your own interactive map (I guess that’s a given since that is what this tutorial is about)
  • Set the default zoom level
  • Locate your geo coordinates
  • Center your map on those coordinates
  • Place a marker on those coordinates
  • Have a custom pop-up with a form to get To Here and From Here Directions
  • Know where to go to learn more

Want to see an example before we start?
You can also see this on a site I created at Vance Auto Sales.

Special Note: Google upgraded their API on April 3, 2006. I modified this code before writing this tutorial to use the new API, so all the new version 2 features should be available if you want to add some in. Also, Google does not provide any kind of routing features in the API. So when a user types in the address to get directions, a real Google Map opens in a new window with directions to or from our location.

Step 1-Sign up for a API Key
Before you can place a map on your own site you need to sign up for a Google API Key.

To sign up, you’ll need to provide the URL of the site that will be using the key. The easiest thing to do is provide the top-level directory that will use the key (rather than the absolute address of the page that will be using the map). Doing this ensures that you’re map will work on any page of your site. For example: I provided http://www.mandladventures.com/
Leave the page with the key in it open, so you can copy and paste the key in later steps. Remember, if you’re testing this on a localhost server, and then uploading it to a production server you’ll need two separate API keys.

Step 2-Locate Your Geo Coordinates
Google doesn’t provide a geocoding service at this time, so you’ll find that on your own.
Geocoder.us is what I used.
Simply enter the address you want to find the coordinates for, and write down the latitude and longitude geocoder.us provides.
Geocoder.us is only for United States addresses. If you live somewhere else, search for free geocoders.

Step 3-Create an XML file
This XML file will store all the points you want to mark on the map. This file also provides the text that will appear when the marker is selected. In our example, we only create one marker. If you want more than one marker on the map, add more instances of the of marker in the XML code below.

<markers>
  <marker lat="35.827818" lng="-86.072576" html="&lt;b&#47;&gt;First Baptist Church&lt;&#47;b&#47;&gt; &lt;br &#47;&gt; 405 West Main Street, &lt;br &#47;&gt; Woodbury, TN 37190" label="FBC"/>
</markers>

Change lat=”35.827818″ to your address’s latitude.
Change lng=”-86.072576″ to your address’s longitude.

Replace “First Baptist Church” with the title of your location.
Change 405 West Main Street, &lt;br /&gt; Woodbury, TN 37190 to your address.
Change the label=”FBC” to whatever you want.
Save the file as map.xml, and upload it to the same directory where your map page will be. You can change the directory, but you will have to change all the references to map.xml in step 7’s code to point to a your directory.

Remember: XML requires all HTML characters to be escaped.
For your convenience, I included a list of commonly escapeed characters below:

< = &lt;
> = &gt;
/ = &#47;
] = &#93;
[ = &#91;
" = &#34;
' = &#39;

Step 4-Call the API with your key
Insert the following code in the head section of your web page, placing your API key between key= and ”

<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAbTgUqmDVtw6KNosttYwutxR-kQiDMsqewHdPfI0JvuxAHQRqVhQsEF-filcfK_gQIlIUCIcFhtJH0Q" type="text/javascript"></script>

Step 5-Add an onunload event to the body tag

<body onunload="GUnload()">

Step 6-Place the div to contain the map

     <div id="map" style="width: 550px; height: 450px; border: 1px solid #000000;"></div>

	 <!--What to display if JavaScript is disabled in the user's browser-->
    <noscript><strong>JavaScript must be enabled in order for you to use Google Maps.</strong><br />
      However, it seems JavaScript is either disabled or not supported by your browser. <br />
      To view Google Maps, enable JavaScript by changing your browser options, and then
      try again.<br /><br />
    </noscript>

Insert this div, where you want to the map to appear.
Change the sytle to fit your needs.

Step 7-Insert the final bit of code
Insert this right before the /body and /html tags at the end of your web page that contains the map.

<script type="text/javascript">
    //<![CDATA[

	//the original code had a GMapSidebar to pick the markers from, I eliminated the GMapSidebar,
	//but deleting the code that referenced the bar corrupted the rest of the code
	//so just ignore references to GMapSidebar, unless you're really with JavaScript
    if (GBrowserIsCompatible()) {
      // this variable will collect the html which will eventually be placed in the GMapSidebar
      var GMapSidebar_html = "";

      // arrays to hold copies of the markers and html used by the GMapSidebar
      // because the function closure trick doesnt work there
      var gmarkers = [];
      var htmls = [];
      var i = 0;
      // arrays to hold variants of the info window html with get direction forms open
      var to_htmls = [];
      var from_htmls = [];

      // A function to create the marker and set up the event window
      function createMarker(point,name,html) {
        var marker = new GMarker(point);

        // The info window version with the "to here" form open (The Directions Form part.)
        to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
           '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" size=40 maxlength=40 name="saddr" id="saddr" value="" /><br>' +
           '<input value="Get Directions" TYPE="submit">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" +
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" size=40 maxlength=40 name="daddr" id="daddr" value="" /><br>' +
           '<input value="Get Directions" type="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" +
           '"/>';
        // The inactive version of the direction info
        html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';

        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        // save the info we need to use later for the GMapSidebar
        gmarkers[i] = marker;
        htmls[i] = html;
        // add a line to the GMapSidebar html
        GMapSidebar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
        i++;
        return marker;
      }

      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        gmarkers[i].openInfoWindowHtml(htmls[i]);
      }

      // functions that open the directions forms
      function tohere(i) {
        gmarkers[i].openInfoWindowHtml(to_htmls[i]);
      }
      function fromhere(i) {
        gmarkers[i].openInfoWindowHtml(from_htmls[i]);
      }

//*******************************************************************
//Edit these options to CONFIGURE THE MAP
      // create the map
      var map = new GMap2(document.getElementById("map"));
	  //GLargeMapControl adds large zoom and pan controls on the left,
	  //you can change it by picking from two of the options described below
	  //there is a GSmallMapControl for a smaller pan/zoom control
	  //also there is GSmallZoomControl - a small zoom control (no panning controls)
      map.addControl(new GLargeMapControl());

	  //this adds the Map, Satellite, and Hybrid buttons, delete line if you don't want it
      map.addControl(new GMapTypeControl());

	  //this adds a scale to the bottom left of the map, delete line if you don't want it
	  map.addControl(new GScaleControl());

	  //type in the Geo Coordinates and default zoom level below. (Latitude, Longitude), Zoom level);
	  //these Coordinates set the center of the map, they do not place the marker.
	  //that is done in the map.xml file. If you want a marker to be centered, type
	  //the same coordinates here that are used for that marker in the map.xml file
	  //0 is zoomed all the way out.
      map.setCenter(new GLatLng(35.827818,-86.072576), 12);
//*******************************************************************

      // Read the data from map.xml
      var request = GXmlHttp.create();
      request.open("GET", "map.xml", true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          var xmlDoc = request.responseXML;
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");

          for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
            var html = markers[i].getAttribute("html");
            var label = markers[i].getAttribute("label");
            // create the marker
            var marker = createMarker(point,label,html);
            map.addOverlay(marker);
          }
          // put the assembled GMapSidebar_html contents into the GMapSidebar div
          document.getElementById("GMapSidebar").innerHTML = GMapSidebar_html;
        }
      }
      request.send(null);
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    // This Javascript is based on code provided by the
    // Blackpool Community Church Javascript Team
    // http://www.commchurch.freeserve.co.uk/
    // http://www.econym.demon.co.uk/googlemaps/
	//slight modifications by Matt from http://www.mandladventures.com/

    //]]>
    </script>

Step 8-Configure the map
Edit this section of the code above.

//*******************************************************************
//Edit these options to CONFIGURE THE MAP
      // create the map
      var map = new GMap2(document.getElementById("map"));
	  //GLargeMapControl adds large zoom and pan controls on the left,
	  //you can change it by picking to of the options described below
	  //there is a GSmallMapControl for a smaller pan/zoom control
	  //also there is GSmallZoomControl - a small zoom control (no panning controls)
      map.addControl(new GLargeMapControl());

	  //this adds the Map, Satellite, and Hybrid buttons, delete line if you don't want it
      map.addControl(new GMapTypeControl());

	  //this adds a scale to the bottom left of the map, delete line if you don't want it
	  map.addControl(new GScaleControl());

	  //type in the Geo Coordinates and default zoom level below. (Latitude, Longitude), Zoom level);
	  //these Coordinates set the center of the map, they do not place the marker.
	  //that is done in the map.xml file. If you want a marker to be centered, type
	  //the same coordinates here that are used for that marker in the map.xml file
	  //0 is zoomed all the way out.
      map.setCenter(new GLatLng(35.827818,-86.072576), 12);
//*******************************************************************

Set the default map center point, and the zoom level.
Change 35.827818 to your latitude
Change -86.072576 to your longitude.
Change 12 to your desired zoom level. 0 is zoomed all the way out.
To delete a control, remove the line of code.
You can change the types of controls used on the map.
For example, some controls can be smaller or bigger, which is useful if you have a small map. I included the alternative control names in the source code comments. For example change GLargeMapControl to GSmallMapControl.

Step 9-Tutorial Complete
Enjoy!


Download the Source Code used in this tutorial.

To learn more check out these resources:

Big Thanks goes to:

  • Mike Williams for writing the tutorials I based my code off of
  • Google for releasing the API

58 Responses to “Google Maps API Tutorial”

  1. Matt says:

    Hi Jerome. I’m not sure if you could put a Flash movie inside a popup when the marker is clicked. I don’t see why you couldn’t though. Interesting idea…I’m not familiar with Flash so I’m afraid I don’t have any tips on how to go about doing it.

    Adding a link to the Flash movie shouldn’t be any trouble. You would just nestle the link like any other text. Just be careful with your use of quotes or your syntax will be wrong and you’ll get errors.

    Hope this helps!

  2. 1.april says:

    thanx a lot :)
    it saved me hours of my enjoyfull life :D

  3. Matt says:

    I’m glad it helped April!

  4. Mike says:

    I’ve taken a ton of source code, mashed them up and to be honest with you, am having trouble getting help with any questions about it due to the fact that there aren’t any maps out there quite like this one –

    I’ve got over 45000 places on a single map, using a clusterer and tabs to dimmy down the load time and make the XML docs smaller. In Firefox the thing loads wonderfully, usually within 2-5 seconds. In IE however, it’s usually between 8-12 seconds, which, to be honest, is much too long, and even after it’s done loading, the map is still a little unresponsive depending on your internet connection. I’ve got a completely comprehensible search function, so you can either search by specific location, or use your own address etc…. Each tab has it’s own custom icons, and there are driving directions in each pop-up info window.

    I’ve been looking in JSON for a better solution, but am having issues getting all my other features to work with it. I can get the map to work just fine, but it’s all the added bonuses that are giving me a headache.

    Matt, can you take a look as I’m out of ideas, and maybe need some third party advice. I’ve tried the other Mike (from Mike’s Little Web Page Tutorials) but don’t get any sort of response. Mozilla rules, IE drools – Too bad IE is in control of Egypt right now, or I’d be in business :)

    http://www.texasbeermaps.com – Click on the “drink map” area. The best way to use everything is to either search by city, address, name of place, etc… It’ll zoom in then you can select the tab for what you’re looking for – Or you can just click the tabs and zoom in yourself… Whichever you prefer :P

    Mike

  5. Matt says:

    Mike,

    You’re right; there probably isn’t too many maps out there like yours. I have no idea what needs to be done to optimize your page. 4500 items is a lot but shouldn’t kill IE that badly. I’m sure Google has many more points on there maps but I don’t know how they do it. Sorry I’m no help.

    Matt

  6. Mike says:

    hehe… no… That was 45,000 :P

    Not 4500….. HUGE difference! LOL

    Thanks anyhow Matt, I think I’ve found a better way to do it!

  7. Rich says:

    Don’t think this is a problem with your code, but I can’t find an answer. I am putting images in the balloon, but when I open it, it sizes the balloon prior to loading the image. this makes the image break out of the balloon and looks a mess. Once it has loaded you can reopen the ballon without a problem

  8. Matt says:

    Rich,

    That is a perplexing problem. Unfortuantely, I’m not enough of a JavaScript expert to help you solve it. Have you tried posting this question to some forums. Also, Mike Williams will probably know how to do it. He’s the real expert behind my code.

    I wish I had a solution for you.
    Matt

Leave a Reply

  • All About Me

    I'm a recent college graduate with a degree in information systems and work as an IS Internal Auditor. I enjoy creating websites and learning about new technology. The best way to get me away from the PC is a good camping trip or mountain bike ride. Want to learn more?