Going beyond MyMaps: Introduction to the Google Maps Javascript API

I’m hoping this blog will get a lot more up to date soon, but I’m still back-filling old projects for now. Here’s my basic tutorial on the Google Maps API that I gave at the 2009 Investigative Reporters and Editors CAR conference in March.

Anyone without any mapping or programming experience can actually do quite a bit with Google MyMaps: add points with a variety of icons, draw lines and polygons, add text to info windows, and do it all quickly.

So when is it time to move beyond that?

  • You have a lot of points (more than a dozen or so) you want to put on the map
  • You have data you want to map in a database or an XML file
  • You want to change the appearance of the map itself (which map type, which controls are available)
  • You want to use complex polylines like county or city boundaries

What do you need to know to get started?

  • HTML
  • CSS
  • A moderate level of Javascript
  • Basic XML principles

Fortunately, you don’t need to spend any money to do even quite advanced Google mapping. You will 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:

  • A browser
  • Firebug is very helpful

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
  4. Keep a tab open for the Google Maps API reference
  5. Load your API key inside the <HEAD> of the HTML document
    <script src=”http://maps.google.com/maps?file=api&v=2&key=[mykeyname]&sensor=false” type=”text/javascript”></script>
  6. Inside your HTML body, create a target <DIV> for your map
    <div id=”map” style=”width : 500px ; height : 400px ; border : 1px solid #000 ;”></div>

  7. Just after document’s </BODY> tag, write Javascript to initialize your map after the entire body of the document has loaded
    <script language=”Javascript”>
    //<![CDATA[

    if (GBrowserIsCompatible()) {

    var map = new GMap2(document.getElementById("map"));

    }
    //]]>
    </script>

  8. Set a center point (lat-long pair) and zoom level for the map
    map.setCenter(new GLatLng(39.769643, -86.158663), 13);
  9. Add this code to the <BODY> tag of your HTML document to prevent memory leaks
    <body onunload=”GUnload()”>

  10. Add a different map type, set the map to use that type
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_PHYSICAL_MAP);

  11. Add some controls to the map for zooming and changing the map type
    map.addControl(new GSmallMapControl());
    map.addControl(new GMenuMapTypeControl());

  12. Let’s add a marker to the map using the default icon. A marker is one type of overlay. Other overlays include lines, polygons, and ground overlays
    var point = new GLatLng(39.769643,-86.158663);
    map.addOverlay(new GMarker(point));

  13. Add an event listener to pop up a label when the user clicks on the icon. From here on out we’ll also create a marker function to keep markers and their behaviors separate from each other. Remember, the function must be declared before the code calls it
    function createMarker(point,html) {
    var marker = new GMarker(point);
    GEvent.addListener(marker, ‘click’, function() {
    marker.openInfoWindowHtml(html);
    });
    return marker;
    }

    var point = new GLatLng(39.769643,-86.158663);
    var testmarker = createMarker(point,”<div style=’color : #CC0000 ;’>Hello, NICAR\</div>”)
    map.addOverlay(testmarker);

  14. Now we’ll load multiple points from a flat XML file. This process uses a custom asynchronous request from Google called GDownloadUrl
    function loadMyLocations(whichxml) {
    GDownloadUrl(whichxml, function(data) {

    var xml = GXml.parse(data);
    var locations = xml.documentElement.getElementsByTagName(“location”);

    });
    }

  15. Set up a basic Javascript loop to get each XML row
    for (var i = 0; i < locations.length; i++) {
    alert(locations[i].getAttribute("label"));
    }

  16. For each row, get the attributes you need and run our marker function as before
    var label = locations[i].getAttribute(“label”);
    var latitude = parseFloat(locations[i].getAttribute(“lat”));
    var longitude = parseFloat(locations[i].getAttribute(“long”));

    var dynamicpoint = new GLatLng(latitude,longitude);
    var dynamicmarker = createMarker(dynamicpoint,label);
    map.addOverlay(dynamicmarker);

  17. For reference, here’s the code for the full page:

    <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
    “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
    <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>
        <meta name=”generator” content=”BBEdit 8.2″ />
        
        <script src=”http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAnXJbcYra5cIfy6uPpLTD6hQ5QqU9rgaQFdjDVk398i-rXfaBgBTE1-zdxRWaL7MjmfClkvNiI-i4KA&sensor=false” type=”text/javascript”></script>
        

    </head>
    <body onunload=”GUnload()”>

    <div id=”map” style=”width : 500px ; height : 400px ; border : 1px solid #000 ;”></div>

    </body>
    <script language=”Javascript”>

        //<![CDATA[

        if (GBrowserIsCompatible()) {
        
            function loadMyLocations(whichxml) {
                GDownloadUrl(whichxml, function(data) {
                    
                    var xml = GXml.parse(data);
                    var locations = xml.documentElement.getElementsByTagName("location");
        
                    for (var i = 0; i < locations.length; i++) {
                    
                        var label = locations[i].getAttribute(“label”);
                        var latitude = parseFloat(locations[i].getAttribute(“lat”));
                        var longitude = parseFloat(locations[i].getAttribute(“long”));
                        
                        var dynamicpoint = new GLatLng(latitude,longitude);
                        var dynamicmarker = createMarker(dynamicpoint,label);
                        map.addOverlay(dynamicmarker);
                        
                        //alert(locations[i].getAttribute(“label”));
                    }
                });
            }
            
            function createMarker(point,html) {
                var marker = new GMarker(point);
                GEvent.addListener(marker, ‘click’, function() {
                    marker.openInfoWindowHtml(html);
                });
                return marker;
            }
        
        
            var map = new GMap2(document.getElementById(“map”));
            map.setCenter(new GLatLng(39.769643, -86.158663), 13);
            
            map.addMapType(G_PHYSICAL_MAP);
            map.setMapType(G_PHYSICAL_MAP);
                        
            map.addControl(new GSmallMapControl());
            map.addControl(new GMenuMapTypeControl());
            
            var point = new GLatLng(39.769643,-86.158663);
            var testmarker = createMarker(point,”<div style=’color : #CC0000 ;’>Hello, NICAR\</div>”);
            map.addOverlay(testmarker);
            
            loadMyLocations(“basicmapxml.xml”);
            
        }
        
        //]]>

    </script>
    </html>

  18. Links for your next steps:

    Google Maps API reference:
    Your new best friend. I still have it open all the time.
    http://code.google.com/apis/maps/documentation/reference.html

    Mike William’s Google Maps Tutorial:
    Indispensable resource, lots of add-ons available
    http://econym.org.uk/gmap/

    ClusterMarker:
    Combine overlapping icons into one grouped icon
    http://googlemapsapi.martinpearman.co.uk/articles.php?cat_id=1

    Google Maps Flash API:
    http://code.google.com/apis/maps/documentation/flash/

If you’ve mastered all these skills, you can already do a lot. But there’s still a lot to learn: move on to overlays, polylines and polygons, and dynamic generation of points using PHP/MySQL in the advanced tutorial.