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:

58 Responses to “Google Maps API Tutorial”

  1. That was really useful; thanks! Very clear, and easy to understand. You can see the results here. I hope that will make it much easier for people to find us. I’ll definitely be reusing this code!

    The only thing bordering on a difficulty I ran into was that I actually have a div called “sidebar”, so it was being slightly mangled when the JavaScript loaded. I just renamed it in the code, however, and all is well. I can also see that some people might be confused as to where to upload the “map.xml” file.

  2. Matt says:

    Andrew, I’m glad it helped. The map looks good on your site.
    I will clear up the map.xml directions, and will see if I can come up with something for the “sidebar”. Maybe I’ll rename sidebar as GMapSidebar, so hopefully no one will be using that code.

  3. Thanks for this tutorial.
    I’m going to bookmark it, and use it on our church site when I get a chance.

  4. Matt says:

    Cool. If you don’t mind, let me know when you get the map on your church site, I’d like to see it. Also, if you have any questions, I’ll do my best to help.

  5. ICTBLOG.it says:

    Google Maps API Tutorial…

    Per chi fosse attratto dal fascino della mappe e vorrebbe poter realizzare una propria mappa con una propria georeferenzazione questa guida fa sicuramente al loro caso.Pochi passaggi, semplici spiegazioni (in lingua inglese) e la mappa da inserire nel …

  6. Matt says:

    ICTBLOG.it: Thanks for the comment. I tried to translate it, but had a little trouble. I wish I knew Italian. If you don’t mind, could you translate this for all the English speaking readers? Thanks for the link from your blog as well. Hope you found this tutorial helpful. If you have any questions, you know where to find me.

  7. [...] It has been about a month since I released my Google Maps API Tutorial and I thought this would be a good time to look back on it. The map tutorial definitely increased my blog stats and helped my Google rank– see included pics. I originally created the tutorial to help out a couple of guys on the Godbit forum and hoped that it would help some more people along the way. You know, just trying to Give Back. [...]

  8. [...] If you search for “google map directions tutorial” my Google Maps API Tutorial is the number 1 search result. I can’t believe it! I just wanted to share my brief moment of fame. To learn out more about my feelings on the tutorial see my Google Maps Reflection post. [...]

  9. Matt Heerema says:

    Woohoo! Very helpful, thanks!

    Check it out in action at the URL for my name here.

  10. Matt says:

    I’m glad it helped Matt!
    Thanks for leaving the link. I always enjoy seeing how people use the code provided.

  11. Matt Heerema says:

    I did, however, change the code in Step 7 (google’s code, I presume, not yours), so that it validates. made sure all HTML tag attributes were in lower case, and in the javascript, all forward slashes need to be escaped with a backslash (ie, “”).

  12. Matt says:

    Thanks for pointing that out. Such a simple mistake to make. Validation and web standards are so important. When I have time, I’ll try to update all my source code.

  13. Matt says:

    Matt Heerema, I finally got around to updating the code. It should be more standards compliant now. Please note that I didn’t change all of the code that appears in the tutorial because I was too lazy, but the source code from the download is correct. Thanks again,

  14. shawn says:

    I recently did a tutorial mashup..
    that is, i combined two tutorials into one working example

    Much of the code is similar because apparently we use the same source for Google Map API Tutorials.. lol.. I used his tutorial on GMaps and JSON.

    The second tutorial I used was written by Dustin Diaz which explained how to write JSON.

    The map itself isn’t anything fancy, it’s the javascript that runs it.

    My Google Map Example – take a look at the source.

    Shawn

  15. Matt says:

    Shawn the source code does look similar, though are maps don’t. I hadn’t heard of JSON, but it sounds pretty cool. I know Dustin Diaz knows his stuff. Nice work on your map. Your second example looks nicer, but the first one is better for someone who wants to see just the map code by itself.

    Thanks for the comment.

  16. gmapsnoob says:

    The tutorials at http://www.econym.demon.co.uk/googlemaps/index.htm advocate setting your mimetype for xml to text/xml, but: http://annevankesteren.nl/2004/08/mime-types has this to say on the matter:
    text/xml is in process of being deprecated and already has serious encoding problems.

  17. Matt says:

    @gmapsnoob,

    Thanks for the heads up on the text/xml mimetype being deprecated. The tutorials at http://www.econym.demon.co.uk/googlemaps/index.htm are not focused on web standards, but they do have some great JavaScript and Google Map example pages. I recommend passing the code through a validator such as the one offered by the W3 to find and then correct any issues like the one you mentioned.

    Thanks again for passing this information along to me. I’ll have to keep it in mind in the future. Before I forget, do you know where the W3 mentions the depreciation of text/xml?

  18. yanu says:

    thank for your tutorial., I’m student from Indonesia.. terima kasih

  19. Matt says:

    Yanu, I’m glad you enjoyed the tutorial. It’s good to know that it’s useful to people from all over the world.

  20. Mike VaVerka says:

    How would I make it so that the Info window automatically comes up rather then having to click on itt? This is the best tutorial by the way :) great job. Thanks for your help

  21. Matt says:

    Mike, I’m afraid your question is more complex than I wish it was. It shouldn’t be hard to open an info window automatically.

    To do so, you need the following code to open an info window in the center of the map.

    marker.openInfoWindowHtml(html);
    

    You should add this line above where the following code appears:

            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 += '' + name + '
    '; i++; return marker; } // This function picks up the click and opens the corresponding info window function myclick(i) { gmarkers[i].openInfoWindowHtml(htmls[i]); }

    Basically, the code above listens for a “click” before opening a info window.

    I think adding that new line of code above the code listening for the click will open the info window automatically and still allow the existing code to open and close that window.

    I haven’t tried this out though, so it may very well not work. It is my best guess. I will be the first to admit that I’m not JavaScript expert. Let me know what happens. If it doesn’t work, maybe I can think something else to try.

    I also recommend checking out the Opening an Info Window section in the Google Maps API Documentation.

  22. comradeRocket says:

    Mike and Matt,
    I’ve been trying to get the info window to open automaticly for a few days now but haven’t had much luck, I have probably already tried what you suggested up there, Matt, I copied and pasted into my code but no luck…

    I came up with something the other day only there ia a serious bug, it works fine in Firefox, doesn’t work in Safari (don’t really care about that), and the info window pops up in Internet Explorer, but IE doesn’t load the map images anymore, maybe somebody can try this and see what I’m not doing right. I don’t know much about JavaScript.

    So here was my thinking. The info window needs an action to open it. I don’t want the user to have to do an action to open it, or atleast not know they are doing an action to open it. So I came to the idea of mouse movment being the action to open the window. I figured chances are more than likely that the user will move the mouse before the map has completey loaded, but the problem with this was every mouse movement acted as a click, so mouse movement opened the window, but the next movement closed it. Out of frustration I took the little red balloon off the map because I am worried that not all users will know to click it, and added a big button above the map that said click here. Then I thought what if the button was hidden and clicked when ever the page loaded, and voila it works… but not so well in IE.

    Here is my code, kinda ugly but again I don’t know much JavaScript.

    Add the following code to your body tag.

    onLoad=”clickButton()”

    When I used Matt’s original code above I didn’t bother putting the script in the head, so it is in the body sitting right above the div that holds the map. Add the following code above the original JavaScript and div holding the map.

    function clickButton()
    {
    document.getElementById(‘button1′).click()
    }

    Get Directions

    And lastly add the following code.

    GEvent.addDomListener(document.getElementById(“button1″), “click”, function() {
    marker.openInfoWindowHtml(html);
    });

    Above this part of Matt’s original code.

    GEvent.addListener(marker, “click”, function() {
    marker.openInfoWindowHtml(html);
    });

    Maybe somebody can figure out why this works fine but stops the map images from loading in IE.

    -Rocket

  23. Matt says:

    Hey Rocket, I don’t know as much JavaScript as I should. The Google Maps stuff is pretty intense JavaScript so I won’t be of much help.

    I would make sure all of your HTML and CSS is valid markup to rule out any problems not associated with the JavaScript. The W3C offers an HTML validator and a CSS validator.

    If you’re still stuck, try contacting Mike Williams. He’s the guy who created the original code from which I based my tutorials.

  24. calvin says:

    matt, great tutorial,

    If i may ask how would one insert the custom icon code into you script.
    I think it would compliment what you have already written perfectly.

    I have tried doing it myself but no joy on the matter, if you get chance could show us an example.

    thanks

    calvin

  25. Matt says:

    Calvin,

    When you tried adding the custom icons yourself, did you follow these directions from Google?

    You’ll need to add all the code under the “// Create our “tiny” marker icon” JavaScript comment. The “icon” variable name used in Google’s example should not conflict with any of my code.

    Once you’ve created the icon with JavaScript, you’ll need to make sure the code displaying the marker calls it. This is where it gets tricky. The snippet of code that Google uses to add the marker is

    map.addOverlay(new GMarker(point, icon));

    This code should replace the following line of my code:

    map.addOverlay(marker);

    I haven’t tested it, but I think it should work. Please let me know what you find out.

    Thanks,
    Matt

  26. calvin says:

    Hi Matt,

    I feel so silly, I do apologize what i did was to add to your existing code the following:

    // arrays to hold variants of the info window html with get direction forms open
    var to_htmls = [];
    var from_htmls = [];
    // A icon descriptives.
    var icon = new GIcon(G_DEFAULT_ICON, “vitalicon.png”);
    icon.iconSize = new GSize(24, 24);

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

    This code now gave me the basis to edit the marker. To fine tune the styling I am now looking at this tutorial
    http://www.econym.demon.co.uk/googlemaps/custom.htm

    which allows to fine tune your icon.

    I hope this helps,

    Calvin

  27. Matt says:

    Hi Calvin,

    I’m not I fully understand your reply. Was it the code you posted in your comment that allowed you to created and edit the custom marker or was it my code? As far as stylizing that marker now that you’ve got it created, I believe you found another great Google Maps tutorial from Mike Williams.

    Once you finalize your map and have it the way you want it, would you please send a link to the website? I’d love to see a working example and take a look at the code. I’m sure other readers of this tutorial would appreciate it as well. Thanks!!!

  28. calvin says:

    matt i have tried to post my responce on your page, your php could not upload it up
    could you email me and ill sent it to you

    regards

    super calvin :P

  29. Calvin says:

    Right let me first start by saying that I have used and followed this tutorial to a Tee.
    Im not at all familiar with javascript so i had to do a bit of experimentation to get my idea to work.

    Background:
    I needed a map for a site that im working on, which allowed users to input there address to see a “from here to there” route.

    Matt’s tutorial perfectly fitted my needs, what I wanted to do was to create a custom marker to jazzy things up a bit, here is the map (works in Firefox).

    http://www.vitalhair.co.uk/vitalmap/map.htm

    as you can see my customer icon sits nicely on the map with an established “onclick area” for the marker.

    All i did to matt’s original code was to add this:

    // A icon descriptives.
    var icon = new GIcon();
    icon.image = “vitalicon.png”;
    icon.iconSize = new GSize(69, 73);
    icon.shadow = “vitaliconshad.png”;
    icon.shadowSize = new GSize(100, 73);
    icon.iconAnchor = new GPoint(33, 73);
    icon.infoWindowAnchor = new GPoint(33, 5);
    icon.transparent = “blank1.png”;

    (for further explanation of these properties please refer to Mike Williams and is Google maps tutorials).

    and finally i changed the variable marker property from this:

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

    TO THIS:

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

    So in effect i just added icon to the above.

    What next:

    so as you can see it works I have my custom marker and works in the firefox browser
    the main problem that I have now is that this map does not work in IE and I believe that I have to had some variable to the script to make it do so.

    So if there are any suggestions please share your ideas and thoughts

    Calvin

    p.s matt feel free to edit this post as you see fit.

  30. Matt says:

    Thanks so much Calvin!!! I’m glad to know how to officially do this now. Nice looking map…that icon sure does jazz things up. Good work.

  31. Michael says:

    Link to source code is not working? Has it been moved or deleted?

    I have tried your code and can not get the map to load and I would very much like to make this work for the site we are working on.

    Feel free to e-mail if you can help.

  32. Michael says:

    Scratch my previous request for help, how do I customize the icon being used by my xml file.

    I know how to make an icon and I think I even understand how to enter the var’s associated with it, but how to I call it out when reading the xml file?

  33. Michael says:

    Abandon my comments, I am learning as I go.

    Map here http://www.floridahaunters.com/map/testmap.html

    This site is for those people who enjoy Haunt Displays. I realize this doesn’t necessarily follow the church based theme of your original code, but it has helped us a lot.

    I have customized the icons accordingly, but how would I go about using different icons for different markers???

    Thanks again for the Tutorial, it really helped.

  34. Matt says:

    Michael,

    I’m glad my code could help you. I don’t mind if it doesn’t follow the church based theme or not. I put the tutorial on the web to help everyone.

    Thanks for letting me know that the link to the source code being broken. I must have deleted yesterday while upgrading this site. The download should work now, but it looks like you got your map working just fine without it.

    I apologize for not being able to respond sooner…you were just too fast learning all this stuff on your own.

    As far as using different icons for different markers, I don’t have the exact code to give you. Based on on the code you’ve go so far, I think you’re on the right path. I can tell you that you need to complete an array of GIcons (each instance points to a different icon image location). You assign location, label, and icon type (array name) in the XML file.

    I think the following tutorial from Mike Williams will help you accomplish what you want. Just look at the example map source code and XML file and you should find everything you’re looking far.

    If you still have questions after reading his code, let me know and I’ll try to answer your question more specifically. However, based on all you’ve done with your map so far I doubt you’ll need any additional help.

    Best of luck to you. Let me know how it goes.

  35. Michael says:

    Matt,

    Thanks your walk through was a true help.

    New question, (I’ll wait to hear your answer this time) ;)

    Can you look at the map

    http://www.floridahaunters.com/map/map.html

    If you open one of the Info windows it appears like there is a part of a rectangular in the top and left of the information.

    Any clue why?

  36. Matt says:

    Michael,

    I’m glad the walk through helped you. I apologize for not personally answering your question last time, but it was so much easier to point you to a tutorial that was already written for exactly what you were looking for :D

    I’m about to head to work so I didn’t have time to look at your code in detail. Rather than make you wait till I can look more closely, I can already tell you that it is an Internet Explorer (IE) specific bug. The maps looks great in Firefox 2 but the rectangles appear in IE 7.

    I’ll try and do a little more research for you later when I have more time, but until then I would try running your code against a HTML and CSS Validator to help track down in quirks related to standardization.

    Thanks,
    Matt

  37. Matt says:

    Michael,

    I’ve spend quite a bit of time looking at your code and trying some different configurations of your map to get it to work properly in IE. I’m fairly certain that your code problems isn’t entirely with the Map code but also with your sites code (no offense intended). The code for your site needs to declare a doctype. I recommend reading Fix Your Site With the Right DOCTYPE!.

    Next, I noticed that your .XML file uses the same label=”name” code for each marker. The value of name should be unique. You can do something as simple as incrementing a number at the end of the name if you don’t have something you want to call it.

    Also, most of your break tags (<br />) leave off the closing forward slash. This should be corrected on both the .html file and the .xml file. Also, in your .html file, all of your image tags (<img=”source” alt=”whatever” />) don’t have the closing forward slash.

    Correcting these should help your site validate and then hopefully work better in IE.

  38. Michael says:

    Matt,

    Thanks! It would appear the DOC Type issue resolved the problem I was having in the info windows. (Smacks head) Shouldn’t have overlooked that.

    I apprecaite your time and effort resolving the problem!

    Your walk through, and of course you, ROCK!

    - Michael

  39. Matt says:

    Michael,

    So glad that fixed you’re problem!!! Don’t feel too bad about over looking the doc-type, seems like that is a common mistake.

    Thanks,
    Matt

  40. [...] wanted to apologize to any of my readers that may have recently tried to use my Google Maps API Tutorial. First off, the code had a bug in it that I was totally unaware of. Robert Adams from the Godbit [...]

  41. [...] You know the Google bot isn’t going to skip over something about itself. Do you think my Google Maps API tutorial’s high rank on Google is a [...]

  42. [...] just help newbies, I appreciate all you do. So in the future, I hope to write more things like my Google Maps Tutorial, RSS Education, and Plugin List that will give back to the community. Let me know if you have any [...]

  43. Alex says:

    Just wanted to say what a superb tutorial this is – thanks Matt, this really helped me out.

  44. Dan K says:

    Getting JavaScript errors when trying this.
    Line: 117
    Char: 11
    Error: ‘document.getElementById(…)’ is null or not an object
    Code: 0
    URL: http://www.mandladventures.com/tutorials/map_tutorial/map.htm

    I don’t know if you’re still updating this page. The script works in Firefox, but throws errors in IE.

  45. Matt says:

    @Alex: Thanks!

    @Dan K., thanks for the info though I’m not actively updating this page. The map does work in IE 7 though it does show the error you pointed out. I’m not too concerned as the map is usable with the JavaScript error. If you know a quick fix, let me know and I’ll see about updating the page. My time has been scarce lately.

    Thanks again!

  46. Dan K says:

    Have you tried more than one marker in the markers file for http://www.mandladventures.com/tutorials/map_tutorial/map.htm
    I’m not sure what the answer is but the map becomes unusable with more than one marker in the marker file in both IE6 and IE7.

  47. Matt says:

    Dan K, no I haven’t tried it with more than one marker in the markers file. I’ve only ever needed one marker. I’m not sure what the answer is either. Does anyone else know? I’m willing to give credit where credit’s due. Have you tried contacting Mike Williams or looking at code examples on his site? He seems to be the Google Maps API / JavaScript expert.

  48. Todd says:

    This tutorial was extremely helpful, straight-forward and greatly appreciated!

  49. Matt says:

    Thanks Todd. I really appreciate your thanks!

  50. Jerome says:

    Hi Matt – thank you so much for this explanation. I had been gaping at other blogs before yours, including Google’s documentation, but that was all a little beyond me, it seems.

    Perhaps you can help with this: as I add markers to the XML file, can I add a Flash movie, or links? The idea would be that a movie starts playing when the marker is clicked. Alternatively I could put a link in the window that appears when the marker is clicked, which opens another pop up window that plays the Flash movie.

    Any suggestions?

  51. 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!

  52. 1.april says:

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

  53. Matt says:

    I’m glad it helped April!

  54. 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

  55. 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

  56. 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!

  57. 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

  58. 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

  • Recent Comments

    • Ubuntu HDMI Sound Configuration (22)
      • Tim: Thanks Matt and Mark!! I now have sound through HDMI on my HTPC. I have Ubuntu 9.04, ASUS EN9400GT with Nvidia....
      • Mark: Thank you. Worked on my Toshiba M300 Laptop running Ubuntu 9.04 Jaunty, with the following modifications: I...
    • Tomato Firmware Option for WRT54GL (9)
      • junn: I just upgrade my brand new wrt54gl to dd-wrt. Do have compare dd-wrt with tomato ? Which is fast and stable ?...
      • brianko: FWIW, after having a year of 1500/300 speeds with Time-Warner (supposedly after the RR-Turbo free upgrade),...
  • 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?