In this chapter, we will cover the following topics:
This chapter is focused on events, which is an important concept in any JavaScript application. Although this chapter is brief, the concepts explained here are very important to understand when working with OpenLayers and mapping applications in general.
Events are fundamental in JavaScript. They are the impulses that allow us to produce a reaction. As programmers of a mapping application, we are interested in reacting when the map zoom changes, when a layer is loaded, or when a feature is added to a layer. Every class, which is susceptible to emit events, is responsible for managing its listeners (those interested in being notified when an event is fired) and also to emit events under certain circumstances.
For example, we can register a function handler that listens for the change:resolution event on the OpenLayers map view instance. Every time the view instance changes its zoom level, it has the responsibility to trigger the change:resolution event, so all its listeners will be notified by the new event.
To help in all this process, OpenLayers has an event class called ol.ObjectEvent that extends the event class (goog.events.Event) from the Google Closure library, which takes care of registering listeners and simplifying the action of firing an event to all of them. In summary, this class allows listeners to perform the following:
Some classes, such as ol.Map, extend the base ol.ObjectEvent class to customized subclasses that are better suited for the specific set of available events. The ol.Map class has an event class called ol.MapEvent that provides some base properties and events. For example, it contains an event called moveend, which needless to say, fires when the map is moved.
The ol.MapEvent class gets further extended by a class called ol.MapBrowserEvent, providing extra methods and events: click and pointerdrag, to name a few. The event object, which is reflective of the action against the map, has additional information, such as the coordinates of the map event and the pixel position of the browser event.
Besides the ol.Map class, many other classes, such as ol.layer.Vector, also emit an abundance of event types (of ol.ObjectEvent). When layer properties, such as extent, opacity, and source change, there's an opportunity to register a subscription (handler or listener) to these events that get published.
As a programmer, you'll need to look at the OpenLayers API documentation, which is accessible from the OpenLayers website (http://openlayers.org), or you can also refer to the source code to find out about the available events that you can register on each class. The source code is also hosted on GitHub (https://github.com/openlayers/ol3).