Skip to main content

base-classes

DG.Class

DG.Class powers the OOP facilities of maps API and is used to create almost all of the classes documented here.

In addition to implementing a simple classical inheritance model, it introduces several special properties for convenient code organization — options, includes and statics.

var MyClass = DG.Class.extend({
initialize: function (greeter) {
this.greeter = greeter;
// class constructor
},

greet: function (name) {
alert(this.greeter + ', ' + name);
},
});

// create instance of MyClass, passing "Hello" to the constructor
var a = new MyClass('Hello');

// call greet method, alerting "Hello, World"
a.greet('World');

Class Factories

You may have noticed that maps API objects are created without using the new keyword. This is achieved by complementing each class with a lowercase factory method:

new DG.Map('map'); // becomes:
DG.map('map');

The factories are implemented very easily, and you can do this for your own classes:

DG.map = function (id, options) {
return new DG.Map(id, options);
};

Inheritance

You use DG.Class.extend to define new classes, but you can use the same method on any class to inherit from it:

var MyChildClass = MyClass.extend({
// ... new properties and methods
});

This will create a class that inherits all methods and properties of the parent class (through a proper prototype chain), adding or overriding the ones you pass to extend. It will also properly react to instanceof:

var a = new MyChildClass();
a instanceof MyChildClass; // true
a instanceof MyClass; // true

You can call parent methods (including constructor) from corresponding child ones (as you do with super calls in other languages) by accessing parent class prototype and using JavaScript's call or apply:

var MyChildClass = MyClass.extend({
initialize: function () {
MyClass.prototype.initialize.call('Yo');
},

greet: function (name) {
MyClass.prototype.greet.call(this, 'bro ' + name + '!');
},
});

var a = new MyChildClass();
a.greet('Jason'); // alerts "Yo, bro Jason!"

Options

options is a special property that unlike other objects that you pass to extend will be merged with the parent one instead of overriding it completely, which makes managing configuration of objects and default values convenient:

var MyClass = DG.Class.extend({
options: {
myOption1: 'foo',
myOption2: 'bar',
},
});

var MyChildClass = DG.Class.extend({
options: {
myOption1: 'baz',
myOption3: 5,
},
});

var a = new MyChildClass();
a.options.myOption1; // 'baz'
a.options.myOption2; // 'bar'
a.options.myOption3; // 5

There's also DG.Util.setOptions, a method for conveniently merging options passed to constructor with the defaults defines in the class:

var MyClass = DG.Class.extend({
options: {
foo: 'bar',
bla: 5
},

initialize: function (options) {
DG.Util.setOptions(this, options);
...
}
});

var a = new MyClass({bla: 10});
a.options; // {foo: 'bar', bla: 10}

Includes

includes is a special class property that merges all specified objects into the class (such objects are called mixins).

var MyMixin = {
foo: function () { ... },
bar: 5
};

var MyClass = DG.Class.extend({
includes: MyMixin
});

var a = new MyClass();
a.foo();

You can also do such includes in runtime with the include method:

MyClass.include(MyMixin);

Statics

statics is just a convenience property that injects specified object properties as the static properties of the class, useful for defining constants:

var MyClass = DG.Class.extend({
statics: {
FOO: 'bar',
BLA: 5,
},
});

MyClass.FOO; // 'bar'

Constructor hooks

If you're a plugin developer, you often need to add additional initialization code to existing classes (e.g. editing hooks for DG.Polyline). Maps API comes with a way to do it easily using the addInitHook method:

MyClass.addInitHook(function () {
// ... do something in constructor additionally
// e.g. add event listeners, set custom properties etc.
});

You can also use the following shortcut when you just need to make one additional method call:

    MyClass.addInitHook('methodName', arg1, arg2,);

Functions

FunctionReturnsDescription
extend( <Object> props ) FunctionExtends the current class given the properties to be included. Returns a Javascript function that is a class constructor (to be called with new).
include( <Object> properties ) Includes a mixin into the current class.
mergeOptions( <Object> options ) Merges options into the defaults of the class.
addInitHook( <Function> fn ) Adds a constructor hook to the class.

DG.Evented

A set of methods shared between event-powered classes (like Map and Marker). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire 'click' event).

map.on('click', function (e) {
alert(e.latlng);
});

Maps API deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function:

function onClick(e) { ... }
map.on('click', onClick);
map.off('click', onClick);

Methods

MethodReturnsDescription
on( <String> type, <Function> fn, <Object> context? ) thisAdds a listener function (fn) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. 'click dblclick').
on( <Object> eventMap ) thisAdds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove}
off( <String> type, <Function> fn?, <Object> context? ) thisRemoves a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to on, you must pass the same context to off in order to remove the listener.
off( <Object> eventMap ) thisRemoves a set of type/listener pairs.
off()thisRemoves all listeners to all events on the object.
fire( <String> type, <Object> data?, <Boolean> propagate? ) thisFires an event of the specified type. You can optionally provide an data object — the first argument of the listener function will contain its properties. The event might can optionally be propagated to event parents.
listens( <String> type ) BooleanReturns true if a particular event type has any listeners attached to it.
once()thisBehaves as on(…), except the listener will only get fired once and then removed.
addEventParent( <Evented> obj ) thisAdds an event parent - an Evented that will receive propagated events
removeEventParent( <Evented> obj ) thisRemoves an event parent, so it will stop receiving propagated events
addEventListener()thisAlias to on(…)
removeEventListener()thisAlias to off(…)
clearAllEventListeners()thisAlias to off()
addOneTimeEventListener()thisAlias to once(…)
fireEvent()thisAlias to fire(…)
hasEventListeners()BooleanAlias to listens(…)

DG.Layer

A set of methods from the Layer base class that all maps API layers use. Inherits all methods, options and events from DG.Evented.

var layer = DG.Marker(latlng).addTo(map);
layer.addTo(map);
layer.remove();

Options

OptionTypeDefaultDescription
paneString'overlayPane'By default the layer will be added to the map's overlay pane. Overriding this option will cause the layer to be placed on another pane by default.

Events

EventDataDescription
addEventFired after the layer is added to a map
removeEventFired after the layer is removed from a map
EventDataDescription
popupopenPopupEventFired when a popup bound to this layer is opened
popupclosePopupEventFired when a popup bound to this layer is closed

Methods

Classes extending DG.Layer will inherit the following methods:

MethodReturnsDescription
addTo( <Map> map) thisAdds the layer to the given map
remove()thisRemoves the layer from the map it is currently active on.
removeFrom( <Map> map ) thisRemoves the layer from the given map
getPane( <String> name? ) HTMLElementReturns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

All layers share a set of methods convenient for binding popups to it.

var layer = DG.Polygon(latlngs).bindPopup('Hi There!').addTo(map);
layer.openPopup();
layer.closePopup();

Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened.

MethodReturnsDescription
bindPopup( <String|HTMLElement|Function|Popup> content, <Popup options> options? ) thisBinds a popup to the layer with the passed content and sets up the neccessary event listeners. If a Function is passed it will receive the layer as the first argument and should return a String or HTMLElement.
unbindPopup()thisRemoves the popup previously bound with bindPopup.
openPopup( <LatLng> latlng? ) thisOpens the bound popup at the specificed latlng or at the default popup anchor if no latlng is passed.
closePopup()thisCloses the popup bound to this layer if it is open. Opens or closes the popup bound to this layer depending on its current state. Returns true if the popup bound to this layer is currently open.
setPopupContent( <String|HTMLElement|Popup> content, <Popup options> options? ) thisSets the content of the popup bound to this layer.
getPopup()PopupReturns the popup bound to this layer.
Extension methods

Every layer should extend from DG.Layer and (re-)implement the following methods.

MethodReturnsDescription
onAdd( <Map> map ) thisShould contain code that creates DOM elements for the layer, adds them to map panes where they should belong and puts listeners on relevant map events. Called on map.addLayer(layer).
onRemove( <Map> map ) thisShould contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer).
getEvents()ObjectThis optional method should return an object like { viewreset: this._reset } for addEventListener. These events will be automatically added and removed from the map with your layer.
beforeAdd( <Map> map ) thisOptional method. Called on map.addLayer(layer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only.

Events inherited from Evented

DG.Control

DG.Control is a base class for implementing map controls. Handles positioning. All other controls extend from this class.

Options

OptionTypeDefaultDescription
positionString'topright'The position of the control (one of the map corners). Possible values are 'topleft', 'topright', 'bottomleft' or 'bottomright'

Methods

MethodReturnsDescription
getPosition()stringReturns the position of the control.
setPosition( <string> position ) thisSets the position of the control.
getContainer()HTMLElementReturns the HTMLElement that contains the control.
addTo( <Map> map ) thisAdds the control to the given map.
remove()thisRemoves the control from the map it is currently active on.

DG.Handler

Abstract class for map interaction handlers.

Methods

MethodReturnsDescription
enable()Enables the handler
disable()Disables the handler
enabled()BooleanReturns true if the handler is enabled

Extension methods

Classes inheriting from Handler must implement the two following methods:

MethodReturnsDescription
addHooks()Called when the handler is enabled, should add event hooks.
removeHooks()Called when the handler is disabled, should remove the event hooks added previously.

DG.Projection

An object with methods for projecting geographical coordinates of the world onto a flat surface (and back). See Map projection.

Maps API uses a Spherical Mercator projection. Assumes that Earth is a sphere.

Methods

MethodReturnsDescription
project( <LatLng> latlng ) PointProjects geographical coordinates into a 2D point.
unproject( <Point> point ) LatLngThe inverse of project. Projects a 2D point into a geographical location.

Properties

PropertyTypeDescription
boundsLatLngBoundsThe bounds where the projection is valid

DG.Renderer

Base class for vector renderer implementations (DG.SVG, DG.Canvas). Handles the DOM container of the renderer, its bounds, and its zoom animation. A Renderer works as an implicit layer group for all DG.Paths

  • the renderer itself can be added or removed to the map. All paths use a renderer, which can be implicit (the map will decide the type of renderer and use it automatically) or explicit (using the renderer option of the path). Do not use this class directly, use DG.SVG and DG.Canvas instead.
Options
OptionTypeDefaultDescription
paddingNumber 0.1How much to extend the clip area around the map view (relative to its size) e.g. 0.1 would be 10% of map view in each direction

Options inherited from Layer

Events

Events inherited from Layer

Methods

Methods inherited from Layer

Methods inherited from Evented

Event objects

Whenever a class inheriting from Evented fires an event, a listener function will be called with an event argument, which is a plain object containing information about the event. For example:

map.on('click', function (ev) {
alert(ev.latlng); // ev is an event object (MouseEvent in this case)
});

The information available depends on the event type:

Event

The base event object. All other event objects contain these properties too.

PropertyTypeDescription
typeStringThe event type (e.g. 'click').
targetObjectThe object that fired the event.

MouseEvent

PropertyTypeDescription
latlngLatLngThe geographical point where the mouse event occured.
layerPointPointPixel coordinates of the point where the mouse event occured relative to the map layer.
containerPointPointPixel coordinates of the point where the mouse event occured relative to the map сontainer.
originalEventDOMMouseEventThe original DOM mouse event fired by the browser.

Properties inherited from Event

LocationEvent

PropertyTypeDescription
latlngLatLngDetected geographical location of the user.
boundsLatLngBoundsGeographical bounds of the area user is located in (with respect to the accuracy of location).
accuracyNumberAccuracy of location in meters.
altitudeNumberHeight of the position above the WGS84 ellipsoid in meters.
altitudeAccuracyNumberAccuracy of altitude in meters.
headingNumberThe direction of travel in degrees counting clockwise from true North.
speedNumberCurrent velocity in meters per second.
timestampNumberThe time when the position was acquired.

Properties inherited from Event

ErrorEvent

PropertyTypeDescription
messageStringError message.
codeNumberError code (if applicable).

Properties inherited from Event

LayerEvent

PropertyTypeDescription
layerILayerThe layer that was added or removed.

Properties inherited from Event

LayersControlEvent

PropertyTypeDescription
layerILayerThe layer that was added or removed.
nameStringThe name of the layer that was added or removed.

Properties inherited from Event

TileEvent

PropertyTypeDescription
tileHTMLElementThe tile element (image).

Properties inherited from Event

TileErrorEvent

PropertyTypeDescription
tileHTMLElementThe tile element (image).

Properties inherited from Event

ResizeEvent

PropertyTypeDescription
oldSizePointThe old size before resize event.
newSizePointThe new size after the resize event.

Properties inherited from Event

GeoJSON event

PropertyTypeDescription
layerILayerThe layer for the GeoJSON feature that is being added to the map.
propertiesObjectGeoJSON properties of the feature.
geometryTypeStringGeoJSON geometry type of the feature.
idStringGeoJSON ID of the feature (if present).

Properties inherited from Event

PropertyTypeDescription

Properties inherited from Event

DragEndEvent

PropertyTypeDescription
distanceNumberThe distance in pixels the draggable element was moved by.

MetaEvent

PropertyTypeDescription
latlngLatLngThe geographical coordinates of the metalayer's point.
metaObjectMetalayer's data.

LangEvent

PropertyTypeDescription
langStringThe current map's language.