Google Maps API hands-on training, part 1

Go to part two of the training
Presumed knowledge:
HTML
Moderate Javascript understanding
CSS
Basic XML
What you’ll need:

  • A Google Maps API key (one per server, make an include)
  • A text editor
  • Some addresses or Lat-Long coordinates
    Where to geocode points:

    • geocoder.us
    • batchgeocode.com (feed it a tab-delimited file of addresses, get one back)
  • A browser
  • Firebug is very helpful

Supporting files:

Getting started:

  1. Make sure you’re using the API appropriately. The good news is that Google has very open terms, but be sure you understand the advertising caveat
  2. Create a basic HTML page
  3. Sign up for an API key at http://code.google.com/apis/maps/signup.html
  4. Keep a tab open for the API reference at http://code.google.com/apis/maps/documentation/reference.html
  5. Load your API key inside the <HEAD> of the HTML document
    [js light="true"]<!–mikejcorey.com key (will work offline, but not if you upload it to another site)–>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAnXJbcYra5cIfy6uPpLTD6hQ5QqU9rgaQFdjDVk398i-rXfaBgBTE1-zdxRWaL7MjmfClkvNiI-i4KA&sensor=false" type="text/javascript"></script>[/js]
  6. Inside your HTML body, create a target <DIV> for your map
    [js light="true"]<div id="map" style="width:500px;height:400px;border:1px solid #000;"></div>[/js]
  7. Inside your document’s </HEAD> tag, write Javascript to initialize your map after the entire body of the document has loaded
    [js light="true"]var objMap; //A variable we declare early so our map is accessible outside the function that creates it.
    //A function that loads when the HTML page is finished loading, which creates the map
    function loadMap() {
    if (GBrowserIsCompatible()) {
    objMap = new GMap2(document.getElementById("map"));
    } else {
    document.getElementById("map").innerHTML = "There’s supposed to be a Google Map here, but your browser isn’t capable of showing it.";
    }
    }[/js]
  8. Set a center point (lat-long pair) and zoom level for the map
    [js light="true"]objMap.setCenter(new GLatLng(33.453814, -112.073239), 12);[/js]
  9. Add this code to the <BODY> tag of your HTML document to initialize the map once the body has finished loading, and to prevent memory leaks
    [js light="true"]<body onload="loadMap()" onunload="GUnload()">[/js]
  10. Add a different map type, set the map to use that type
    [js light="true"]objMap.addMapType(G_PHYSICAL_MAP);
    objMap.setMapType(G_PHYSICAL_MAP);[/js]
  11. Add some controls to the map for zooming and changing the map type
    [js light="true"]objMap.addControl(new GLargeMapControl());
    objMap.addControl(new GMapTypeControl());[/js]
  12. A marker is one type of overlay. Other overlays include lines, polygons, and ground overlays. There’s several ways to add markers to the map. Let’s start with the simplest method, and add a marker to the map using the default icon.
    [js light="true"]//The simplest way to add a marker
    var objBasicPoint = new GLatLng(33.453814, -112.073239);
    var objBasicMarker = new GMarker(objBasicPoint);
    objMap.addOverlay(objBasicMarker);[/js]
  13. That’s fine if we don’t want too many markers and we don’t want them to do much, but as soon as you get over about 5 markers, this approach becomes impractical. Writing a function that can be called over and over is a good way to handle multiple markers. Inside the function we’ll also add an event listener to pop up a label (called an InfoWindow) when the user clicks on the icon.
    [js light="true"]//Our function for creating markers with event listeners
    function createMarker(objPoint,strHTML,strIconName) {
    var objMarker = new GMarker(objPoint,{ icon:strIconName });
    GEvent.addListener(objMarker, ‘click’, function() {
    objMarker.openInfoWindowHtml(strHTML);
    });
    return objMarker;
    }

    //Adding a marker the more useful way, using a function
    var objPoint = new GLatLng(33.479035, -112.047882);
    var strWindowContent = "<div style=’color:#CC0000;width:200px;’><b>Barrio Cafe\</b><br/>Azcentral.com raves: Superb Mexican food in a funky setting.\</div>";
    var objTestMarker = createMarker(objPoint,strWindowContent);
    objMap.addOverlay(objTestMarker);[/js]

  14. If you have more than one type of data you want to show on the map, you’ll want to use a different color or shape of icon. You can make custom markers with any .PNG image file with a transparent background. Photoshop will work fine, but Adobe Fireworks is even better for this. We won’t cover creating the icon image here, so we’re starting with an image that we know the pixel dimensions of. For this map we’re going to use two icons that are the same shape, but are different sizes. First we’ll tell Google some key information about both icons. We’ll declare these variables before our other functions and outside of those functions, so we can access the markers from anywhere in the script.
    [js light="true"]//marker definitions
    var objBaseIcon = new GIcon();
    objBaseIcon.shadow = "http://www.mikejcorey.com/nicar2010/images/shadow-stop.png";
    objBaseIcon.iconSize = new GSize(19, 25);
    objBaseIcon.shadowSize = new GSize(32, 25);
    objBaseIcon.iconAnchor = new GPoint(9, 25);
    objBaseIcon.infoWindowAnchor = new GPoint(9, 1);[/js]
  15. Now we’ll define the different icons, which will be based on our baseicon, and put the icons into an array for easy reference later.
    [js light="true"]var objRedIcon = new GIcon(objBaseIcon);
    objRedIcon.image = "http://www.mikejcorey.com/nicar2010/images/stop.png";

    var objGreenIcon = new GIcon(objBaseIcon);
    objGreenIcon.image = "http://www.mikejcorey.com/nicar2010/images/start.png";

    var arrMapIcons = [objRedIcon,objGreenIcon];[/js]

  16. If you want to load marker data from a database, or if you’d like to be able to easily change the markers, you’ll want to load markers dynamically from XML or JSON. In this example we’ll load multiple points from a flat XML file. This process uses a custom asynchronous request from Google called GDownloadUrl.
    [js light="true"]//function for retrieving list of points from XML
    function loadMyLocations(strWhichXML) {
    GDownloadUrl(strWhichXML, function(data) {
    var objXML = GXml.parse(data);
    var objLocations = objXML.documentElement.getElementsByTagName("location");

    });
    }[/js]

  17. Set up a basic Javascript loop to get each XML row
    [js light="true"]for (var numI = 0; numI < objLocations.length; numI++) {
    }[/js]
  18. For each row, get the attributes you need and run our marker function as before
    [js light="true"]var objLocationItem = objLocations[numI];
    var numMarkerLabel = objLocationItem.getAttribute("label");
    var numMarkerIcon = objLocationItem.getAttribute("markertype");
    var numMarkerLat = parseFloat(objLocationItem.getAttribute("lat"));
    var numMarkerLng = parseFloat(objLocationItem.getAttribute("lng"));
    var objPoint = new GLatLng(numMarkerLat, numMarkerLng);
    var strWindowContent = "<div style=’color:#CC0000;’>" + numMarkerLabel + "\</div>";
    var objMarker = createMarker(objPoint,strWindowContent,arrMapIcons[numMarkerIcon]);
    objMap.addOverlay(objMarker);[/js]
  19. That’s all for part one. Here’s the code for the entire page:
  20. [js light="true"]
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>My awesome first Google map</title>
    <!–mikejcorey.com key (will work offline, but not if you upload it to another site)–>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAnXJbcYra5cIfy6uPpLTD6hQ5QqU9rgaQFdjDVk398i-rXfaBgBTE1-zdxRWaL7MjmfClkvNiI-i4KA&sensor=false" type="text/javascript"></script>
    <script language="Javascript">
    //<![CDATA[
    var objMap; //A variable we declare early so our map is accessible outside the function that creates it.

    //marker definitions
    var objBaseIcon = new GIcon();
    objBaseIcon.shadow = "http://www.mikejcorey.com/nicar2010/images/shadow-stop.png";
    objBaseIcon.iconSize = new GSize(19, 25);
    objBaseIcon.shadowSize = new GSize(32, 25);
    objBaseIcon.iconAnchor = new GPoint(9, 25);
    objBaseIcon.infoWindowAnchor = new GPoint(9, 1);
    var objRedIcon = new GIcon(objBaseIcon);
    objRedIcon.image = "http://www.mikejcorey.com/nicar2010/images/stop.png";

    var objGreenIcon = new GIcon(objBaseIcon);
    objGreenIcon.image = "http://www.mikejcorey.com/nicar2010/images/start.png";

    var arrMapIcons = [objRedIcon,objGreenIcon];
    //A function that loads when the HTML page is finished loading, which creates the map
    function loadMap() {
    if (GBrowserIsCompatible()) {

    objMap = new GMap2(document.getElementById("map"));
    objMap.setCenter(new GLatLng(33.453814, -112.073239), 12);

    objMap.addMapType(G_PHYSICAL_MAP);
    objMap.setMapType(G_PHYSICAL_MAP);

    objMap.addControl(new GLargeMapControl());
    objMap.addControl(new GMapTypeControl());

    //The simplest way to add a marker
    var objBasicPoint = new GLatLng(33.453814, -112.073239);
    var objBasicMarker = new GMarker(objBasicPoint);
    objMap.addOverlay(objBasicMarker);

    //Adding a marker the more useful way, using a function
    var objPoint = new GLatLng(33.479035, -112.047882);
    var strWindowContent = "<div style=’color:#CC0000;width:200px;’><b>Barrio Cafe\</b><br/>Azcentral.com raves: Superb Mexican food in a funky setting.\</div>";
    var objTestMarker = createMarker(objPoint,strWindowContent);
    objMap.addOverlay(objTestMarker);

    //Or we can just load a bunch of points from an XML file
    loadMyLocations("basicmapxml.xml");
    } else {
    document.getElementById("map").innerHTML = "There’s supposed to be a Google Map here, but your browser isn’t capable of showing it.";
    }
    }

    //Our function for creating markers with event listeners
    function createMarker(objPoint,strHTML,strIconName) {
    var objMarker = new GMarker(objPoint,{ icon:strIconName });
    GEvent.addListener(objMarker, ‘click’, function() {
    objMarker.openInfoWindowHtml(strHTML);
    });
    return objMarker;
    }

    //function for retrieving list of points from XML
    function loadMyLocations(strWhichXML) {
    GDownloadUrl(strWhichXML, function(data) {

    var objXML = GXml.parse(data);
    var objLocations = objXML.documentElement.getElementsByTagName("location");

    for (var numI = 0; numI < objLocations.length; numI++) {
    var objLocationItem = objLocations[numI];

    var numMarkerLabel = objLocationItem.getAttribute("label");
    var numMarkerIcon = objLocationItem.getAttribute("markertype");
    var numMarkerLat = parseFloat(objLocationItem.getAttribute("lat"));
    var numMarkerLng = parseFloat(objLocationItem.getAttribute("lng"));

    var objPoint = new GLatLng(numMarkerLat, numMarkerLng);
    var strWindowContent = "<div style=’color:#CC0000;’>" + numMarkerLabel + "\</div>";
    var objMarker = createMarker(objPoint,strWindowContent,arrMapIcons[numMarkerIcon]);
    objMap.addOverlay(objMarker);
    }
    });
    }
    //]]>
    </script>
    </head>
    <body onload="loadMap()" onunload="GUnload()">
    <div id="map" style="width:500px;height:400px;border:1px solid #000;"></div>
    </body>
    </html>
    [/js]

Go to part two of the training