English | Site Directory

Google Maps API

Google Maps API Premier

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

Events

Map Events Overview

JavaScript within the browser is event driven, meaning that JavaScript responds to interactions by generating events, and expects a program to listen to interesting events. For example, within browsers, user mouse and keyboard interactions create events that propagate within the DOM. Programs interested in certain events will register JavaScript event listeners for those events and execute code when those events are received.

The Google Maps API adds to this event model by defining custom events for Maps API objects. It is important to note that the Maps API events are separate and distinct from the standard DOM events. However, as different browsers implement different DOM event models, the Maps API also provides mechanisms to listen for and respond to these DOM events without needing to handle the various cross-browser peculiarities.

Event Listeners

Events in the Google Maps API are handled by using utility functions within the GEvent namespace to register event listeners. Each Maps API object exports a number of named events. For example, the GMap2 object exports click, dblclick, and move events, and a host of others as well. Each event happens within a given context, and can pass arguments that identify that context. For example, the mousemove event fires when the user moves the mouse within a map object, and passes the GLatLng of the geographic location in which the mouse is located.

For a complete list of GMap2 events and the arguments they generate, see GMap2.Events.

To register for notification of these events, use the static method GEvent.addListener(). That method takes an object, an event to listen for, and a function to call when the specified event occurs. For example, this code snippet shows an alert every time the user clicks on the map:

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
GEvent.addListener(map, "click", function() {
  alert("You clicked the map.");
});

View example (event-simple.html)

Listeners are also able to capture the context of the event. In the following example code, we display the latitude and longitude of the center of the map after the user drags the map.

var map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "moveend", function() {
  var center = map.getCenter();
  document.getElementById("message").innerHTML = center.toString();
});
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

View example (event-context.html)

Using Closures in Event Listeners

When executing an event listener, it is often advantageous to have both private and persistent data attached to an object. JavaScript does not support "private" instance data, but it does support closures which allows inner functions to access outer variables. Closures are useful within event listeners to access variables not normally attached to the objects on which events occur.

The following example uses a function closure in the event listener to assign a secret message to a set of markers. Clicking on each marker will review a portion of the secret message, which is not contained within the marker itself.

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

// Creates a marker at the given point
// The five markers show a secret message when clicked
// but that message is not within the marker's instance data

function createMarker(point, number) {
  var marker = new GMarker(point);
  var message = ["This","is","the","secret","message"];
  marker.value = number;
  GEvent.addListener(marker, "click", function() {
    var myHtml = "<b>#" + number + "</b><br/>" + message[number -1];
    map.openInfoWindowHtml(point, myHtml);
  });
  return marker;
}

// Add 5 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 < 5; i++) {
  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
    southWest.lng() + lngSpan * Math.random());
  map.addOverlay(createMarker(point, i + 1));
}

View example (event-closure.html)

Using Passed Arguments in Events

Many events in the Maps API event system pass arguments when the event is triggered. For example, the GMap2 "click" event passes an overlay and overlaylatlng if the map click occurs on an overlay; otherwise, it passes a latlng of the map coordinate. You can access these arguments by passing the specified symbols directly to the functions within the event listeners.

In the example below, we first test to ensure the click was on a map tile by checking if the latlng argument is defined; if so, we open an info window above the clicked coordinate and display the coordinate converted to pixel space along with the zoom level.

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

GEvent.addListener(map,"click", function(overlay, latlng) {     
  if (latlng) { 
    var myHtml = "The GPoint value is: " + map.fromLatLngToDivPixel(latlng) + " at zoom level " + map.getZoom();
    map.openInfoWindow(latlng, myHtml);
  }
});
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());

View example (event-arguments.html)

Binding Events to Object Methods

Functions are useful when you wish to attach event listeners to particular instances of an object. If instead, you wish to invoke a method on all instances of an object in response to events, you can use GEvent.bind(). In the following example, an application class instance binds map events to its own methods, modifying class state when events are triggered:

function MyApplication() {
  this.counter = 0;
  this.map = new GMap2(document.getElementById("map"));
  this.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  GEvent.bind(this.map, "click", this, this.onMapClick);
}

MyApplication.prototype.onMapClick = function() {
  this.counter++;
  alert("You have clicked the map " + this.counter + " " +
        (this.counter == 1 ? "time" : "times"));
}

var application = new MyApplication();

View example (event-bind.html)

Listening to DOM Events

The Google Maps API event model creates and manages its own custom events. However the DOM also creates and dispatches its own events, according to the particular browser event model in use. If you wish to capture and respond to these events, the Google Maps API provides browser-neutral wrappers to listen and bind DOM events, without the need for custom code.

The GEvent.addDomListener() static method registers an event handler for a DOM event on a DOM node. Similarly, the static method GEvent.bindDom() allows you to register event handlers for DOM events on class instances.

Removing Event Listeners

When an event listener is no longer needed, you should remove it. This might even be needed in cases where the event should only be fired once. Removing event listeners that were defined via anonymous functions within closures can be difficult. However, the addListener(), addDomListener(), bind(), and bindDom() functions return a GEventListener handle, which can be used to eventually deregister the handler.

The following example responds to a click by placing a marker on the map. Any subsequent click removes the event listener. Notice that the removeOverlay() code is never executed as a result. Also, notice that you can remove an event listener even from within the event listener itself.

function MyApplication() {
  this.counter = 0;
  this.map = new GMap2(document.getElementById("map"));
  this.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  var myEventListener = GEvent.bind(this.map, "click", this, function(overlay, latlng) {
    if (this.counter == 0) {
      if (latlng) {
        this.map.addOverlay(new GMarker(latlng))
        this.counter++;
      } else if (overlay instanceof GMarker) {
        this.removeOverlay(marker)
      }
    } else {
      GEvent.removeListener(myEventListener);
    }
  }); 
}

function load() {
  var application = new MyApplication();
}

View example (event-removal.html)