1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

A brief introduction to Google Maps

What is Google Maps?

  • Web mapping service application
  • Street maps
  • Satellite maps
  • Route planner
  • Street views
  • Based on JavaScript with JSON (JavaScript Object Notation) data transfer

Google Maps API

  • Free visualisation API
  • JavaScript
  • Customise Google Maps to application-specific requirements
    • Markers, lines, images, links, regions,...

Associated services

  • Geo-coders - map addresses and locations to (latitude, longitude)
  • Add KML (keyhole markup langage) overlays
  • Get directions
  • Add adverts
  • Many and varied...

Copyright, licencing and usage

  • Your data + Google Map = "derived data"
    • Google has copyright
    • Explains the Google logo and copyright branded on maps
  • Terms and conditions preclude development of "competitor" apps
    • e.g. route finders
  • Google reserve the right to add adverts in future

World view

  • World coordinate system - (latitude, longitude)
  • Uses Mercator projection
    • No coverage of the poles

A walkthrough

We now walk through using the Google Maps API 2 from an HTML web page via JavaScript.

To do this walkthrough you will need your own web server:

  • You will need to sign up for a Google account if you don't already have one. These are free and you can sign up at http://www.google.com/accounts.
  • You will also need to be able to set up a publicly-accessible web server or already have access to one into which you can put HTML documents.
  • If your organisation gives you a directory in your home directory for your own web pages then you can use that and your documents can just go in there.
  • If you don't have these but have have access to a server outwith any firewalls that is publicly-accessible then you could just download Apache Tomcat, start it up and put your HTML documents into their webapps/jsp-examples directory (in which case your web page URL below would be http://host:port/jsp-examples/googlemap.html).

Download the HTML page

Copy this HTML into a file and make it available on your web server.

<!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">
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <title>Google Maps</title>

</head>
 <body>

  <h2>Google Maps</h2>
 
</body>
</html>

View page in browser

Start up a browser and visit the page googlemap.html. There's nothing much to it, yet!

Add a placeholder element for the Google Map

The Google Maps API works by replacing a named HTML element in the HTML page with the Google Map. So we need to add one. We'll use a div element, so add the following in the body element beneath the h2 heading:

  <div id="map" style="width: 800px; height: 500px"></div>

The id is used to tell this element apart from any other div elements we may have in our HTML document. The size will determine the size of the Google Map.

Add a JavaScript method to build the Google Map

We invoke the Google Map APIs using JavaScript so we need to add a JavaScript function that we can call. Add the following within the head element of your document:

  <script type="text/javascript">

   function load() 
   {
     // Check whether the browser is compatible.
     if (GBrowserIsCompatible()) 
     {
     }
   }
  </script>

and edit the body element so it invokes this when the page is loaded:

 <body onload="load()" onunload="GUnload()">

But if you try to reload the page you may see an error in the status bar of your browser. This is because our JavaScript is invoking methods that it doesn't know about, Google Maps API methods like GBrowserIsCompatible and GUnload. So, we need to import these. Add the following element in the head element, before the script element you added before:

  <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key="GOOGLE-API-KEY" 
          type="text/javascript">
  </script>

Note you should keep the script elements separate - don't combine them into one script element.

Refresh your page. You should get a warning pop-up:

This web site needs a different Google Maps API key. A new key can be generated at http://code.google.com/apis/maps

Get a Google Maps API key

To use Google Maps requires a Google Maps API key. This is linked to your host name and your Google account.

Google recommend getting a key for a URL like http://www.uni.ac.uk) since this covers all sub-directories, sub-domains and port numbers.

The URL used to get the key must match that which you'll use in your browser.

  • If you use IP numbers then your URL needs to specify IP numbers.
  • If you use localhost then you'll need to register http://localhost.

To get your key visit http://code.google.com/apis/maps

Click "Sign up for a Google Maps API key" on the right-hand side for the page

Scroll down and click the checkbox "I have read and agree with the terms and conditions".

Enter your your server URL.

Enter your Google account username and password.

Take a copy of your Google API key. This is a long value like

ABXQIAAAAzENYImGeEWFVbQWMYAXXn0yohRf7CYWocT6QcaCqKf1gSHq_TkJt87nhRQGtA

In your document, replace GOOGLE-API-KEY with your key e.g. replace

  <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key="GOOGLE-API-KEY" 
          type="text/javascript">
  </script>

with:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABXQIAAAAzENYImGeEWFVbQWMYAXXn0yoocT6QcaCqKf1gSHq_TkJtGtA" 
        type="text/javascript">

If you reload your page you it should succeed with no warnings in the browser's status bar.

Add the Google Map

Now, as we mentioned, a named HTML element is substituted with a map so we need do this. Add the following line within the if statement to replace an element with ID map (which is our div element) with a Google Map.

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

We also get a variable, map, that we can then manipulate to control the look of our map.

If you refresh your browser you'll see a map container.

Centre the map

Let's centre the map so we can see something recognisable. Add the following:

       map.setCenter(new GLatLng(55.923804,-3.17668), 14);

This centre's the map on the given latitude and longitude (that of The University of Edinburgh's Kings Buildings) with a default zoom level of 14.

Change the map style

There are a number of map styles available. These include:

  • G_NORMAL_MAP - the default, usually a street map.
  • G_SATELLITE_MAP - a satellite image.
  • G_HYBRID_MAP - a hybrid of the normal and satellite images.

You can change the map style by calling:

       map.setMapType(G_HYBRID_MAP); 

Add some map controls

It can be good to let the user decide what view they want. To do this we can add a Google Map control. These are widgets that control the map's presentation.

So, to add a widget to allow the user to choose the map style, add:

        map.addControl(new GMapTypeControl());  

To provide a widget to allow the user to scroll the map using buttons and zoom in and out, add:

        map.addControl(new GSmallMapControl());  

Instead of the above you could use GLargeMapControl which has a zoom bar, or just add zoom in and out buttons with no scroll buttons using GSmallZoomControl.

You could also add a smaller-scale overview map:

       map.addControl(new GOverviewMapControl()); 

Add a marker

We can now annotate the map with our data or other things of interest, customising it to what we want it to show. The simplest thing we can do is add a simple push-pin marker, so add the lines:

       var marker = new GMarker(new GLatLng(55.923804,-3.17668));
       map.addOverlay(marker);

If you refresh your browser you'll see a push-pin over Kings Buildings.

Add a pop-up balloon for the marker

We can add a balloon that gives more information about the location that we've marked. Add the lines:

        var html="<h3>Kings Buildings</h3><p>Mayfield Road, Edinburgh</p>";
        marker.openInfoWindowHtml(html);

Refresh the page and you'll see there's a pop-up balloon linked to the point.

Add an event handler

Only one balloon (or information window as they're termed) can be visible at any time. This isn't so useful if we want a pop-up for each "thing" we've put on the map. So, we can add an event handler to our marker. Replace the two lines above with the following:

       GEvent.addListener(marker, "click", function() 
       { 
         var html="<h3>Kings Buildings</h3><p>Mayfield Road, Edinburgh</p>";
         marker.openInfoWindowHtml(html); 
       });

Refresh the page. Now the balloon will only appear if you click on the marker.

So, let's add another marker and pop-up. Add:

       var junction = new GMarker(new GLatLng(55.923804,-3.16668));
       map.addOverlay(junction);
       GEvent.addListener(junction, "click", function() 
       { 
         var html="<h3>Liberton Road Junction</h3>";
         html += "<ul><li>A major artery for traffic heading into the city</li>";
         html += "<li><a href=\"http://www.camerontoll.co.uk/\">Cameron Toll</a> is accessible on foot from here </li>";
         html += "</ul>";
         junction.openInfoWindowHtml(html); 
       });

Refesh the page then click on each in turn. This code also shows how we can easily embed hyperlinks into our pop-ups.

Add some lines

We can also add lines to our map. The following creates a "polyline" made up of a number of points, to provide a boundary round Kings Buildings and its neighbourhood. The colour (yellow) and line width (10) are also specified:

       var boundary = new GPolyline([ 
        new GLatLng(55.913804,-3.15668),
        new GLatLng(55.913804,-3.18668),
        new GLatLng(55.933804,-3.18668),
        new GLatLng(55.933804,-3.15668),
        new GLatLng(55.913804,-3.15668)
      ], "#fffacd", 10); 
      map.addOverlay(boundary);

Straight lines added like this do not take into account the curvature of the earth so Google Maps also supports the notion of "geodesic" lines to take this into account.

Add an image

We can add, or overlay, images on top of our map. The following adds a photo of Kings Buildings:

      var boundaries = new GLatLngBounds(new GLatLng(55.921004,-3.17868), 
                                         new GLatLng(55.923004,-3.16968)); 
      var overlay = new GGroundOverlay("http://www2.ph.ed.ac.uk/~wjh/pictures/JCMB.jpg", boundaries); 
      map.addOverlay(overlay);

The boundaries state the bounds of the image in terms of latitudes and longitudes. The picture will resize accordingly if you zoom in or out of the map.

Google Maps API 3

  • Just
  • Many API changes but the basic principles are the same
    • Create map, add widgets to it
  • Intended to be
    • More usable - no API key is needed for a start
    • Faster
    • Mobile-friendly

Resources

This page was written with the aid of the following resources:

Example Google Map HTML 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">
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <title>Google Maps</title>
  <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=GOOGLE-API-KEY"
          type="text/javascript">
  </script>
  <script type="text/javascript">

   function load() 
   {
     // Check whether the browser is compatible.
     if (GBrowserIsCompatible()) 
     {
       var map = new GMap2(document.getElementById("map"));
       // Centre the map - latitude, longitude, zoom.
       map.setCenter(new GLatLng(55.923804,-3.17668), 14);
       // Map types. G_NORMAL_MAP is default if none is chosen.
       // map.setMapType(G_NORMAL_MAP);  
       // map.setMapType(G_SATELLITE_MAP);  
       map.setMapType(G_HYBRID_MAP); 
       // Allow user to select map type.
       map.addControl(new GMapTypeControl());  
       // Arrows, zoom +|-.
       map.addControl(new GSmallMapControl());  
       // Or arrows, zoom bar.
       // map.addControl(new GLargeMapControl());  
       // Or zoom +|- only.
       // map.addControl(new GSmallZoomControl());  
       // Smaller scale map in corner.
       map.addControl(new GOverviewMapControl()); 
       // Add a marker.
       var marker = new GMarker(new GLatLng(55.923804,-3.17668));
       map.addOverlay(marker);
       /**
       var html="<h3>Kings Buildings</h3><p>Mayfield Road, Edinburgh</p>";
       marker.openInfoWindowHtml(html);
       */
       // Add an event handler for mouse clicks on the marker.
       GEvent.addListener(marker, "click", function() 
       { 
         var html="<h3>Kings Buildings</h3><p>Mayfield Road, Edinburgh</p>";
         // Pop-up a balloon when clicked.
         marker.openInfoWindowHtml(html); 
       }); 
       // Add a new marker.
       var junction = new GMarker(new GLatLng(55.923804,-3.16668));
       map.addOverlay(junction);
       // Add an event handler for mouse clicks on the marker.
       GEvent.addListener(junction, "click", function() 
       { 
         var html="<h3>Liberton Road Junction</h3>";
         html += "<ul><li>A major artery for traffic heading into the city</li>";
         html += "<li><a href=\"http://www.camerontoll.co.uk/\">Cameron Toll</a> is accessible on foot from here </li>";
         html += "</ul>";
         // Pop-up a balloon when clicked.
         junction.openInfoWindowHtml(html); 
       });
       // Create a poly-line. Specify the points, the colour and the 
       // width.
       var boundary = new GPolyline([ 
        new GLatLng(55.913804,-3.15668),
        new GLatLng(55.913804,-3.18668),
        new GLatLng(55.933804,-3.18668),
        new GLatLng(55.933804,-3.15668),
        new GLatLng(55.913804,-3.15668)
      ], "#fffacd", 10); 
      map.addOverlay(boundary);
      // Define boundaries for an overlay.
      var boundaries = new GLatLngBounds(new GLatLng(55.921004,-3.17868), 
                                         new GLatLng(55.923004,-3.16968)); 
      var overlay = new GGroundOverlay("http://www2.ph.ed.ac.uk/~wjh/pictures/JCMB.jpg", boundaries); 
      map.addOverlay(overlay);
     }
   }
  </script>

</head>
 <body onload="load()" onunload="GUnload()">

  <h2>Google Maps</h2>
  <!-- div width and height determines the map size. -->
  <div id="map" style="width: 800px; height: 500px"></div>

</body>
</html>

Example Google Map 3.0 HTML page

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
  <title>Google Maps 3</title>
  <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
  <script type="text/javascript">
  function load() 
  { 
    var centerPoint = new google.maps.LatLng(55.923804, -3.17668); 
    // Set up map size and controls.
    var myOptions = 
    { 
      // Centre the lap - latitude, longitude, zoom.    
      center: centerPoint, 
      zoom: 14, 
      // Map types. google.maps.MapTypeId.ROADMAP is default if none
      //  is chosen.
      // mapTypeId: google.maps.MapTypeId.ROADMAP,
      // mapTypeId: google.maps.MapTypeId.SATELLITE,
      mapTypeId: google.maps.MapTypeId.HYBRID,
      // Allow user to select map type.
      mapTypeControl: true,
      // Set way in which selection is done.
      mapTypeControlOptions: 
      {
        // style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        // style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
        // Default. Based on map size and device running map.
        style: google.maps.MapTypeControlStyle.DEFAULT,
        // Set position. One of TOP, TOP_LEFT, TOP_RIGHT
        // BOTTOM, BOTTOM_LEFT, BOTTOM_RIGHT, LEFT, RIGHT
        position: google.maps.ControlPosition.TOP_LEFT
      },
      // Allow user to navigate.
      navigationControl: true,
      // Set way in which navigation is done.
      navigationControlOptions: 
      { 
        // Zoom +|-.
        // style: google.maps.NavigationControlStyle.SMALL 
        // Arrows, zoom +|-.
        // style: google.maps.NavigationControlStyle.ZOOM_PAN
        // Small zoom +|-
        // style: google.maps.NavigationControlStyle.ANDROID
        // Default. Based on map size and device running map.
        style: google.maps.NavigationControlStyle.DEFAULT,
        position: google.maps.ControlPosition.TOP_RIGHT
      }
    }; 
    // Create map.
    var map = new google.maps.Map(document.getElementById("map"), myOptions); 
    // Add a marker.
    var point = new google.maps.LatLng(55.923804,-3.17668);
    var html = "<h3>Kings Buildings</h3><p>Mayfield Road, Edinburgh</p>";
    var marker = new google.maps.Marker({ 
      position: point,  
      map: map,  
      title:"EPCC"
    }); 
    var popup = new google.maps.InfoWindow({ 
      content: html
    }); 
    google.maps.event.addListener(marker, 'click', function() 
    { 
      popup.open(map, marker); 
    }
    );
    // Add a new marker.
    var junctionPoint = new google.maps.LatLng(55.923804,-3.16668);
    junctionHTML = "<h3>Liberton Road Junction</h3>";
    junctionHTML += "<ul><li>A major artery for traffic heading into the city</li>";
    junctionHTML += "<li><a href=\"http://www.camerontoll.co.uk/\">Cameron Toll</a> is accessible on foot from here </li>";
    junctionHTML += "</ul>";
    var junction = new google.maps.Marker({ 
      position: junctionPoint,  
      map: map,  
      title:"Liberton Road Junction"
    }); 
    var popupJunction = new google.maps.InfoWindow({ 
      content: junctionHTML
    }); 
    google.maps.event.addListener(junction, 'click', function() 
    { 
      popupJunction.open(map, junction); 
    });
    // Create a poly-line. Specify the points, the colour and the 
    // width.
    var coordinates = [
        new google.maps.LatLng(55.913804,-3.15668),
        new google.maps.LatLng(55.913804,-3.18668),
        new google.maps.LatLng(55.933804,-3.18668),
        new google.maps.LatLng(55.933804,-3.15668),
        new google.maps.LatLng(55.913804,-3.15668)
    ];
    var boundary = new google.maps.Polyline({
     path: coordinates,
     strokeColor: "#fffacd",
     strokeWeight: 10
    })
    boundary.setMap(map);
  }
  </script>

</head>
 <body onload="load()">

  <h2>Google Maps 3</h2>
  <!-- div width and height determines the map size. -->
  <div id="map" style="width: 800px; height: 500px"></div>

</body>
</html>