English | Site Directory

Google Maps API

Google Maps API Premier

Same great maps plus a SLA, support, and control over ads

Map Basics

Introduction

The fundamental element in any Google Maps API application is the "map" itself. This document discusses usage of the fundamental GMap2 object and the basics of map operations.

The "Hello, World" of Google Maps

The easiest way to start learning about the Google Maps API is to see a simple example. The following web page displays a 500x300 map centered on Palo Alto, California:

<!DOCTYPE html "-//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 JavaScript API Example</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=abcdefg"
            type="text/javascript"></script>
    <script type="text/javascript">

    function initialize() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
      }
    }

    </script>
  </head>
  <body onload="initialize()" onunload="GUnload()">
    <div id="map_canvas" style="width: 500px; height: 300px"></div>
  </body>
</html>

You can look at this example and download it to edit and play around with it, but you'll have to replace the key in that file with your own Maps API key. (If you register a key for a particular directory, it works for all subdirectories as well.)

Even in this simple example, there are five things to note:

  1. We include the Maps API JavaScript using a script tag.
  2. We create a div element named "map_canvas" to hold the Map.
  3. We write a JavaScript function to create a "map" object.
  4. We center the map on a given geographic point.
  5. We initialize the map object from the body tag's onLoad event.

These steps are explained below.

Loading the Google Maps API

<script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg"
        type="text/javascript">
</script>

The http://maps.google.com/maps?file=api&v=2&key=abcdefg URL points to the location of the JavaScript file that includes all of the symbols and definitions you need for using the Google Maps API. Your page must contain a script tag pointing to this URL, using the key you received when you signed up for the API. In this example the key is shown as "abcdefg."

Map DOM Elements

<div id="map_canvas" style="width: 500px; height: 300px"></div>

For the map to display on a web page, we must reserve a spot for it. Commonly, we do this by creating a named div element and obtaining a reference to this element in the browser's document object model (DOM).

In the example above, we define a div named "map_canvas" and set its size using style attributes. Unless you specify a size explicitly for the map using GMapOptions in the constructor, the map implicitly uses the size of the container to size itself.

GMap2 - the Elementary Object

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

The JavaScript class that represents a map is the GMap2 class. Objects of this class define a single map on a page. (You may create more than one instance of this class - each object will define a separate map on the page.) We create a new instance of this class using the JavaScript new operator.

When you create a new map instance, you specify a DOM node in the page (usually a div element) as a container for the map. HTML nodes are children of the JavaScript document object, and we obtain a reference to this element via the document.getElementById() method.

This code defines a variable (named map) and assigns that variable to a new GMap2 object. The function GMap2() is known as a constructor and its definition (condensed for clarity from the Google Maps API Reference) is shown below:

Constructor Description
GMap2(container, opts?) Creates a new map inside the given HTML container, which is typically a DIV element. You may also pass optional parameters of type GMap2Options in the opts parameter.

Note that because JavaScript is a loosely typed language, we do not need to pass any optional parameters in the constructor, and we don't do so here.

Initializing the Map

  map.setCenter(new GLatLng(37.4419, -122.1419), 13);

Once we've created a map via the GMap2 constructor, we need to do one more thing: initialize it. This initialization is accomplished with use of the map's setCenter() method. The setCenter() method requires a GLatLng coordinate and a zoom level and this method must be sent before any other operations are performed on the map, including setting any other attributes of the map itself.

Loading the Map

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

While an HTML page renders, the document object model (DOM) is built out, and any external images and scripts are received and incorporated into the document object. To ensure that our map is only placed on the page after the page has fully loaded, we only execute the function which constructs the GMap2 object once the <body> element of the HTML page receives an onload event. Doing so avoids unpredictable behavior and gives us more control on how and when the map draws.

The onload attribute is an example of an event handler. The Google Maps API also provides a number of events that you can "listen" for to determine state changes. See Maps Events and Event Listeners for more information.

The GUnload() function is a utility function designed to prevent memory leaks.

Latitudes and Longitudes

Now that we have a map, we need a way to refer to locations on the map. The GLatLng object provides such a mechanism within the Google Maps API. You construct a GLatLng object, passing its parameters in the order { latitude, longitude } as is customary in cartography:

  var myGeographicCoordinates = new GLatLng(myLatitude, myLongitude)

Note: the process of turning an address into a geographic point is known as geocoding and is discussed in detail in the Google Maps API Services section.

Just as it is useful to easily refer to a geographic point, it is also useful to define the geographic bounds of an object. For example, a map displays a current "window" of the entire world within what is known as a viewport. This viewport can be defined by the rectangular points at its corners. The GLatLngBounds object provides this functionality, defining a rectangular region using two GLatLng objects representing the southwest and northeast corners of the bounding box, respectively.

GLatLng objects have many uses within the Google Maps API. The GMarker object takes a GLatLng in its constructor, for example, and places a marker overlay on the map at the given geographic location.

The following example uses getBounds() to return the current viewport, and then randomly places 10 markers on the map within those bounds:

function initialize() {
  var map = new GMap2(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(37.4419, -122.1419), 13);
 
  // Add 10 markers to the map at random locations
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var lngSpan = northEast.lng() - southWest.lng();
  var latSpan = northEast.lat() - southWest.lat();
  for (var i = 0; i < 10; i++) {
    var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
        southWest.lng() + lngSpan * Math.random());
    map.addOverlay(new GMarker(point));
  }
}

View example (map-markers.html)

Note: more information on GMarker objects is within the Overlays section.

Map Attributes

By default, maps show up within the Google Maps API using standard "painted" tiles. However, the Google Maps API also supports other maps types. The following map types are standard:

  • G_NORMAL_MAP- the default view
  • G_SATELLITE_MAP - showing Google Earth satellite images
  • G_HYBRID_MAP - showing a mixture of normal and satellite views
  • G_DEFAULT_MAP_TYPES - an array of these three types, useful for iterative processing

You can set the map type using the GMap2 object's setMapType() method. For example, the following code sets the map to use the satellite view from Google Earth:

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

A map also contains a number of attributes that are useful to ascertain. For example, to find the dimensions of the current viewport, use the GMap2 object's getBounds() method to return a GLatLngBounds value.

Each map also contains a zoom level, which defines the resolution of the current view. Zoom levels between 0 (the lowest zoom level, in which the entire world can be seen on one map) to 19 (the highest zoom level, down to individual buildings) are possible within the normal maps view. Zoom levels vary depending on where in the world you're looking, as data in some parts of the globe is more defined than in others. Zoom levels up to 20 are possible within satellite view.

You can retrieve the current zoom level in use by the map by using the GMap2 object's getZoom() method.

More about zoom levels, map tiles, and creating your own custom map types is available in the Tile Overlays section.

Map Interactions

Now that you have a GMap2 object, you can interact with it. The basic map object looks and behaves a lot like the map you interact with on the Google Maps website and comes with a lot of built-in behavior. The GMap2 object also provides a number of configuration methods to alter the behavior of the map object itself.

By default, map objects tend to react to user activity as they do on http://maps.google.com. You can alter this behavior with a number of utility methods, however. For example, the GMap2.disableDragging() method disables the ability to click and drag the map to a new location.

You can also interact with the map programmatically. The GMap2 object supports a number of methods that alter the map state directly. For example, the setCenter(), panTo, and zoomIn() methods operate on the map programatically, rather than through user interaction.

The following example displays a map, waits two seconds, and then pans to a new center point. The panTo method centers the map at a given point. If the specified point is in the visible part of the map, then the map pans smoothly to the point; if not, the map jumps to the point.

var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
window.setTimeout(function() {
  map.panTo(new GLatLng(37.4569, -122.1569));
}, 1000);

View example (map-animate.html)

More complex interactions are accomplished through use of Maps API Events.

Info Windows

Each map within the Google Maps API may show a single "info window" of type GInfoWindow, which displays HTML content in a floating window above the map. The info window looks a little like a comic-book word balloon; it has a content area and a tapered stem, where the tip of the stem is at a specified point on the map. You can see the info window in action by clicking a marker in Google Maps.

The GInfoWindow object has no constructor. An info window is automatically created and attached to the map when you create the map. You can't show more than one info window at a time for a given map, but you can move the info window and change its contents as needed.

The GMap2 object provides an openInfoWindow() method, which takes a point and an HTML DOM element as arguments. The HTML DOM element is appended to the info window container, and the info window window tip is anchored to the given point.

The GMap2's openInfoWindowHtml() method is similar, but it takes an HTML string as its second argument rather than a DOM element.

To create an info window, call the openInfoWindow method, passing it a location and a DOM element to display. The following example code displays an info window anchored to the center of the map with a simple "Hello, world" message.

var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.openInfoWindow(map.getCenter(),
                   document.createTextNode("Hello, world"));

View example (map-infowindow.html)

For full documentation on info windows, consult the Google Maps API Reference