GEOG5870/1M: Web-based GIS A course on web-based mapping

The Google Maps API

Having direct access to the API allows programmers to exert control over a number of aspects include the general configuration and layout of the map, as well as create new markers and draw on the map surface. The API covers such aspects as:

In practice, there are several APIs rather than a single one. In this module, we concentrate on the JavaScript API for web mapping. Other APIs available include a static API which allows simple maps to be created without using JavaScript. There are also separate APIs for Google Earth, and for various spatial services such as geocoding and route finding.

So how do we use the API? Below is a sample piece of example code distributed by Google that demonstrates a simple use. The code is JavaScript embedded into a web page. In total, this document embeds a map focussed on Sydney, which fills the whole of the browser window.

In the next part, you will use the web page code below to create your first mash-up. Look through it and see if you can guess what some of it is doing. We'll break it down for you below.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
   html { height: 100% }
   body { height: 100%; margin: 0px; padding: 0px }
</style>

<script type="text/javascript"
   src="http://maps.google.com/maps/api/js">
</script>
<script type="text/javascript">
function initialize() {
   var latlng = new google.maps.LatLng(-34.397, 150.644);
   var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);
}
</script>
</head>

<body onload="initialize()">
   <div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Breakdown of the code

The file is a typical HTML document, which contains some JavaScript (note the script tags that contain the code). Like all HTML documents, it contains two sections – a HEAD section and a BODY section. The BODY section is very simple – it contains a single element, a DIV tag that uses an optional style parameter to fill the whole window (note the width and height), and has an ID:

<body onload="initialize()">
   <div id="map_canvas" style="width:100%; height:100%"></div>
</body>

Giving an element an ID allows us to refer to it individually using JavaScript, and therefore to manipulate it. The BODY element also has a JavaScript function name ("initialize()") linked to the event word "onload". "onload" is the name of an event the browser listens out for. The onload event happens when the page has finished loading, at which point this function "initialize()" will be triggered. "onload" is a generic JavaScript event, rather than anything to do with Google. You can find details of others on w3Schools, but we'll come back to events shortly and look at another useful one.

(NB: This example was taken from the Google Maps API website).

Firstly, note that the file commences with <!DOCTYPE html>. This defines the document type as HTML. This is actually a bit of a fudge for an older tag that said what version of HTML it was. This has gone, but without this replacement tag, the version of HTML used by the browser may vary, so including this forces the latest default behaviour (currently HTML 5).

The HEAD section of the document contains four elements: a META tag, a STYLE block and two SCRIPT blocks; here are the first two:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
   html { height: 100% }
   body { height: 100%; margin: 0px; padding: 0px }
</style>

The META tag is used here to define characteristics of how the page should be displayed (in this case, full-screen and not resizeable) – and is significant for display on mobile devices. In this module, we concentrate on traditional desktop and laptop displays, and thus do not need to worry about the viewport (if you're interested in using this to help with mobile phone display etc., see this w3schools tutorial). The STYLE block contains CSS, you could place any CSS here but this code used to ensure that the map fills the whole window (i.e. height and width = 100%)

The two SCRIPT blocks are the most significant parts. The first block loads the Google Maps library into the browser, and provides the functionality for our maps.

<script type="text/javascript"
   src="http://maps.google.com/maps/api/js">
</script>

The library contains all the client-side JavaScript for interacting with Google Maps and Google's server through their API. Once we've linked to the library and it is loaded by the browser it is available for us to use. The block contains a src parameter, which specifies a web location from which the library is to be loaded.

The second SCRIPT block, which starts on the following line, defines the function – "initialize()" – which is run after the page is loaded - remember this is via the 'onload' event. The function sets up some variables that will act as parameters, and then creates a map variable:

<script type="text/javascript">
function initialize() {
   var latlng = new google.maps.LatLng(-34.397, 150.644);
   var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   var map =
      new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);
}
</script>

The first variable declared is called latlng, and as the name might suggest, it is a latitude-longitude position. As we will see when we move onto the introductory material on JavaScript, it is straightforward to declare basic variables such as numbers, strings (i.e. text), and arrays of other variables. In this example, we create a new instance of an object that is defined in the JavaScript library loaded in the first script block; the type of this object is LatLng, formally google.maps.LatLng, i.e. the LatLng type within the google.maps library/package. JavaScript is case sensitive, and thus the correct capitalisation is required. When creating a new instance of this LatLng object, we supply a latitiude and longitude as parameters. We'll cover this in more detail in the next unit.

Note: Javascript has inheritance like other object-oriented languages, so objects can be of a "type" which picks up all the properties and methods of that type plus any types that type is, in turn, based on. However, in Javascript this is actually based on a slightly different system from the common "class" based inheritance you see in things like Java. Javascript uses a "prototype" system where inheritance is based on copying objects of a specific type and adding new stuff to them, rather than using classes as templates. This has its pros and cons - for example, you can change inherited types on the fly, which you may consider a pro and a con depending on your personality. In practice, however, since 2015 you've been able to write Javascript classes, as the standard now includes a class keyword as syntactic sugar hiding this complexity and presenting the whole thing as a standard class-based inheritance framework. If you're interested, you can find out more on Wikipedia and MDN.

Anyhow, back to the script; the second variable created is an "object literal" – essentially an on-the-fly object constructed by saying in one go what is inside it (intro):

   var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };

The object literal here is called myOptions, and will be used to supply customisation options to the maps (note it includes the LatLng just created). Here it is in use:

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);

This object literal is defined using a compact notation known as JSON - JavaScript Object Notation (JSON is used for a wide variety of purposes now, but this is where it started). Three characteristics are given: an initial zoom level,  a center (using the latlng location that we have just defined) and a mandatory map type. In this case, the type is ROADMAP, which is the standard Google Maps map view. The map type is defined by refering to one of the hardwired properties of google.maps.MapTypeId; other types include SATELLITE, HYBRID and TERRAIN.

Finally, the second script block creates the new map object, using the statement:

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);

A new object, called 'map', is created as an instance of the object google.maps.Map. Two parameters are supplied for the construction of this map: firstly, a node in the HTML document, and secondly the set of map options that has been created in the preceding statement. The node is the part of the document which will be modified to display the map (map_canvas); this is a DIV within the BODY part of the HTML document. We refer to this using something called the Document Object Model(DOM).

The Document Object Model

We are not going to cover the DOM in much detail here, but it is worth knowing that it is a language independent API which converts the HTML document to a tree structure containing nodes. Each DIV in the document can then be accessed programmatically. In short, the DOM allows you to change the appearence, structure and content of DIVs in the HTML file using Javascript. This is particularly useful when paired with Javascript events. For example, the user clicks a button with an 'onclick' event attached and Javascript used the DOM to update the content of a HTML div. See example here. In this case we use the DOM to place a map object in the map_canvas element. The code document.getElementById() in the above script tells Javascript where to place the map.


[ Next: Creating your First Google Map ]
[Course Index]