Google Maps JavaScript API v2 (Deprecated)

Google Maps JavaScript API V2 Events

Version 2 of the JavaScript API has been turned down

Warning: Version 2 of the Google Maps JavaScript API is no longer available. Please follow the guide to migrate your code to version 3 of the Google Maps JavaScript API. As of November 19, 2013, all applications requesting v2 are served a special, wrapped version of the v3 API instead. We expect this wrapped version of the API to work for most simple maps, but we strongly encourage you to migrate to the v3 API immediately.

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.");
});

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));
}

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());

Binding Events to Objects

Events typically act directly on the object receiving the event. For example, if you attach a 'click' event listener to a GMap2 object, you usually call methods on the map itself within the event listener's attached function.

You can test this behavior within your code by replacing a reference to the object to this; if the event listener acts on the object receiving the event, both this and the object reference are equivalent.

# The following event listeners are equivalent:

# Access the map using the 'map' symbol
var map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "moveend", function() {
  var center = map.getCenter();
  document.getElementById("message").innerHTML = center.toString();
});

# Access the map using the 'this' keyword
var map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "moveend", function() {
  var center = this.getCenter();
  document.getElementById("message").innerHTML = center.toString();
});

If instead, you wish to invoke a method on a separate object in response to events, you can use GEvent.bind() to bind a method to a different object than the one receiving the event.

In the following example, the event listener binds map 'click' events to an instance of the Counter object, and invokes a method defined within that object:

function initialize() {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_canvas"));
    var myCounter = new Counter();
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    GEvent.bind(map, "click", myCounter, myCounter.increment);
  }
}
    
function Counter() {
  this.counter = 0;
}
    
Counter.prototype.increment = function() {
  this.counter++;
  alert("You have clicked the map " + this.counter +
        (this.counter == 1 ?" time":" times"));
}

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();
}

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.