Same great maps plus a SLA, support, and control over ads
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.
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)
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)
Many events in the Maps API event system pass arguments when the event is triggered.
For example, the GMap2 "click" event passes two arguments (overlay,point)
in the event. You can access these arguments by passing the specified symbols directly to the functions
within the event listeners.
For example, the "click" event on a map passes an overlay and point argument. We
pass these arguments directly within the callback function to invoke within the event listerner.
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
// ground overlay
GEvent.addListener(map,"click", function(overlay,point) {
var myHtml = "The GPoint value is: " + map.fromLatLngToDivPixel(point) + " at zoom level " + map.getZoom();
map.openInfoWindow(point, myHtml);
});
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
View example (event-arguments.html)
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)
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.
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(marker,point) {
if (this.counter == 0) {
if (point) {
this.map.addOverlay(new GMarker(point))
this.counter++;
} else {
this.removeOverlay(marker)
}
} else {
GEvent.removeListener(myEventListener);
}
});
}
function load() {
var application = new MyApplication();
}