Skip to main content

map

This section describes the central class of the maps API which is used to create a map on a page and manipulate it.

DG.Map

Usage example

Initialize the map on the "map" div with a given center and zoom:

var map = DG.map('map', {
center: [54.98, 82.89],
zoom: 13,
});

Creation

FactoryDescription
DG.map( <String> id, <Map options> options? ) Instantiates a map object given the DOM ID of a <div> element and optionally an object literal with Map options.
DG.map( <HTMLElement> el, <Map options> options?) Instantiates a map object given an instance of a <div> HTML element and optionally an object literal with Map options.

Options

OptionTypeDefaultDescription
preferCanvasBoolean falseWhether Paths should be rendered on a Canvas renderer. By default, all Paths are rendered in a SVG renderer.

Control Options

OptionTypeDefaultDescription
zoomControlBoolean trueWhether a zoom control is added to the map by default.
fullscreenControlBoolean trueWhether a fullscreen control is added to the map by default.

Interaction Options

OptionTypeDefaultDescription
closePopupOnClickBoolean trueSet it to false if you don't want popups to close when user clicks the map.
zoomSnapNumber 1Forces the map's zoom level to always be a multiple of this, particularly right after a fitBounds() or a pinch-zoom. By default, the zoom level snaps to the nearest integer; lower values (e.g. 0.5 or 0.1) allow for greater granularity. A value of 0 means the zoom level will not be snapped after fitBounds or a pinch-zoom.
zoomDeltaNumber 1Controls how much the map's zoom level will change after a zoomIn(), zoomOut(), pressing + or - on the keyboard, or using the zoom controls. Values smaller than 1 (e.g. 0.5) allow for greater granularity.
trackResizeBoolean trueWhether the map automatically handles browser window resize to update itself.
boxZoomBoolean trueWhether the map can be zoomed to a rectangular area specified by dragging the mouse while pressing the shift key.
doubleClickZoomBoolean trueWhether the map can be zoomed in by double clicking on it and zoomed out by double clicking while holding shift. If passed 'center', double-click zoom will zoom to the center of the view regardless of where the mouse was.
draggingBoolean trueWhether the map be draggable with mouse/touch or not.
geoclickerBoolean | Objectfalse {/* TODO: translation */}
projectDetectorBooleantrue {/* TODO: translation */}
tilesCheckBoolean true {/* TODO: translation */}
museumBooleantrueWhether the message about unsupported browser will be displayed.

Map State Options

OptionTypeDefaultDescription
centerLatLng undefinedInitial geographic center of the map
zoomNumber undefinedInitial map zoom level
minZoomNumber undefinedMinimum zoom level of the map. Overrides any minZoom option set on map layers.
maxZoomNumber undefinedMaximum zoom level of the map. Overrides any maxZoom option set on map layers.
layersLayer[] []Array of layers that will be added to the map initially
maxBoundsLatLngBounds nullWhen this option is set, the map restricts the view to the given geographical bounds, bouncing the user back when he tries to pan outside the view. To set the restriction dynamically, use setMaxBounds method.
rendererRenderer *The default method for drawing vector layers on the map. DG.SVG or DG.Canvas by default depending on browser support.
poiBoolean true {/* TODO: translation */}
currentLangstring''Language of user interface (see Localization)

Animation Options

OptionTypeDefaultDescription
fadeAnimationBoolean trueWhether the tile fade animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
markerZoomAnimationBoolean trueWhether markers animate their zoom with the zoom animation, if disabled they will disappear for the length of the animation. By default it's enabled in all browsers that support CSS3 Transitions except Android.
transform3DLimitNumber 2^23Defines the maximum size of a CSS translation transform. The default value should not be changed unless a web browser positions layers in the wrong place after doing a large panBy.
zoomAnimationBoolean trueWhether the map zoom animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android.
zoomAnimationThresholdNumber 4Won't animate zoom if the zoom difference exceeds this value.

Panning Inertia Options

OptionTypeDefaultDescription
inertiaBoolean *If enabled, panning of the map will have an inertia effect where the map builds momentum while dragging and continues moving in the same direction for some time. Feels especially nice on touch devices. Enabled by default unless running on old Android devices.
inertiaDecelerationNumber 3000The rate with which the inertial movement slows down, in pixels/second².
inertiaMaxSpeedNumber InfinityMax speed of the inertial movement, in pixels/second.
easeLinearityNumber 0.2
worldCopyJumpBoolean falseWith this option enabled, the map tracks when you pan to another "copy" of the world and seamlessly jumps to the original one so that all overlays like markers and vector layers are still visible.
maxBoundsViscosityNumber 0.0If maxBounds is set, this option will control how solid the bounds are when dragging the map around. The default value of 0.0 allows the user to drag outside the bounds at normal speed, higher values will slow down map dragging outside bounds, and 1.0 makes the bounds fully solid, preventing the user from dragging outside the bounds.

Keyboard Navigation Options

OptionTypeDefaultDescription
keyboardBoolean trueMakes the map focusable and allows users to navigate the map with keyboard arrows and +/- keys.
keyboardPanDeltaNumber 80Amount of pixels to pan when pressing an arrow key.

Mousewheel options

OptionTypeDefaultDescription
scrollWheelZoomBoolean | StringtrueWhether the map can be zoomed by using the mouse wheel. If passed 'center', it will zoom to the center of the view regardless of where the mouse was.
wheelDebounceTimeNumber 40Limits the rate at which a wheel can fire (in milliseconds). By default user can't zoom via wheel more often than once per 40 ms.
wheelPxPerZoomLevelNumber 50How many scroll pixels (as reported by DG.DomEvent.getWheelDelta) mean a change of one full zoom level. Smaller values will make wheel-zooming faster (and vice versa).

Touch interaction options

OptionTypeDefaultDescription
tapBoolean trueEnables mobile hacks for supporting instant taps (fixing 200ms click delay on iOS/Android) and touch holds (fired as contextmenu events).
tapToleranceNumber 15The max number of pixels a user can shift his finger during touch for it to be considered a valid tap.
touchZoomBoolean *Whether the map can be zoomed by touch-dragging with two fingers. If passed 'center', it will zoom to the center of the view regardless of where the touch events (fingers) were. Enabled for touch-capable web browsers except for old Androids.
bounceAtZoomLimitsBoolean trueSet it to false if you don't want the map to zoom beyond min/max zoom and then bounce back when pinch-zooming.

Events

Layer events

EventDataDescription
layeraddLayerEventFired when a new layer is added to the map.
layerremoveLayerEventFired when some layer is removed from the map

Map state change events

EventDataDescription
zoomlevelschangeEventFired when the number of zoomlevels on the map is changed due to adding or removing a layer.
resizeEventFired when the map is resized.
unloadEventFired when the map is destroyed with remove method.
viewresetEventFired when the map needs to redraw its content (this usually happens on map zoom or load). Very useful for creating custom overlays.
loadEventFired when the map is initialized (when its center and zoom are set for the first time).
zoomstartEventFired when the map zoom is about to change (e.g. before zoom animation).
movestartEventFired when the view of the map starts changing (e.g. user starts dragging the map).
zoomEventFired repeteadly during any change in zoom level, including zoom and fly animations.
moveEventFired repeteadly during any movement of the map, including pan and fly animations.
zoomendEventFired when the map has changed, after any animations.
moveendEventFired when the center of the map stops changing (e.g. user stopped dragging the map).
projectchangeProjectEvent {/* TODO: translation */}
projectleaveProjectEvent {/* TODO: translation */}
entranceshowEvent{/* TODO: translation */}
entrancehideEvent{/* TODO: translation */}
poihoverMetaEvent{/* TODO: translation */}
poileaveMetaEvent{/* TODO: translation */}
langchangeLangEvent{/* TODO: translation */}
EventDataDescription
popupopenPopupEventFired when a popup is opened in the map
popupclosePopupEventFired when a popup in the map is closed
autopanstartFired when the map starts autopanning when opening a popup.

Interaction events

EventDataDescription
clickMouseEventFired when the user clicks (or taps) the map.
dblclickMouseEventFired when the user double-clicks (or double-taps) the map.
mousedownMouseEventFired when the user pushes the mouse button on the map.
mouseupMouseEventFired when the user releases the mouse button on the map.
mouseoverMouseEventFired when the mouse enters the map.
mouseoutMouseEventFired when the mouse leaves the map.
mousemoveMouseEventFired while the mouse moves over the map.
contextmenuMouseEventFired when the user pushes the right mouse button on the map, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press).
keypressEventFired when the user presses a key from the keyboard while the map is focused.
preclickMouseEventFired before mouse click on the map (sometimes useful when you want something to happen on click before any existing click handlers start running).

Animation Events

EventDataDescription
zoomanimZoomAnimEventFired on every frame of a zoom animation

Location Events

EventDataDescription
locationerrorErrorEventFired when geolocation (using the locate method) failed.
locationfoundLocationEventFired when geolocation (using the locate method) went successfully.

Methods

MethodReturnsDescription
getRenderer( <Path> layer) RendererReturns the instance of Renderer that should be used to render the given Path. It will ensure that the renderer options of the map and paths are respected, and that the renderers do exist on the map.

Methods for Layers and Controls

MethodReturnsDescription
addLayer( <Layer> layer) thisAdds the given layer to the map
removeLayer( <Layer> layer) thisRemoves the given layer from the map.
hasLayer( <Layer> layer) BooleanReturns true if the given layer is currently added to the map
eachLayer( <Function> fn, <Object> context?) this Iterates over the layers of the map, optionally specifying context of the iterator function.
map.eachLayer(function(layer){ layer.bindPopup('Hello'); }); 
openPopup( <Popup> popup) thisOpens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).
openPopup( <String|HTMLElement> content, <LatLng> latlng, <Popup options> options?) thisCreates a popup with the specified content and options and opens it in the given point on a map.
closePopup(<Popup> popup?) thisCloses the popup previously opened with openPopup (or the given one).
addControl( <Control> control) thisAdds the given control to the map
removeControl( <Control> control) thisRemoves the given control from the map

Methods for modifying map state

MethodReturnsDescription
setView( <LatLnt> center, <Number> zoom, <Zoom/Pan options> options?) thisSets the view of the map (geographical center and zoom) with the given animation options.
setZoom( <Number> zoom, <Zoom/Pan options> options) thisSets the zoom of the map.
zoomIn( <Number> delta?, <Zoom options> options?) thisIncreases the zoom of the map by delta (zoomDelta by default).
zoomOut( <Number> delta?, <Zoom options> options?) thisDecreases the zoom of the map by delta (zoomDelta by default).
setZoomAround( <LatLng> latlng, <Number> zoom, <Zoom options> options) thisZooms the map while keeping a specified geographical point on the map stationary (e.g. used internally for scroll zoom and double-click zoom).
setZoomAround( <Point> offset, <Number> zoom, <Zoom options> options) thisZooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary.
fitBounds( <LatLngBounds> bounds, <fitBounds options> options) thisSets a map view that contains the given geographical bounds with the maximum zoom level possible.
fitWorld( <fitBounds options> options?) thisSets a map view that mostly contains the whole world with the maximum zoom level possible.
panTo( <LatLng> latlng, <Pan options> options?) thisPans the map to a given center.
panBy( <Point> offset) thisPans the map by a given number of pixels (animated).
setMaxBounds( <Bounds> bounds) thisRestricts the map view to the given bounds (see the maxBounds option).
setMinZoom(<Number> zoom)thisSets the lower limit for the available zoom levels (see the minZoom option).
setMaxZoom(<Number> zoom)thisSets the upper limit for the available zoom levels (see the maxZoom option).
panInsideBounds( <LatLngBounds> bounds, <Pan options> options?) thisPans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any.
invalidateSize(<Zoom/Pan options> options)thisChecks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default. If options.pan is false, panning will not occur. If options.debounceMoveend is true, it will delay moveend event so that it doesn't happen often even if the method is called many times in a row.
invalidateSize(<Boolean> animate)thisChecks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default.
stop()thisStops the currently running panTo or flyTo animation, if any.
flyTo( <LatLng> latlng, <Number> zoom?, <Zoom/Pan options> options?) thisSets the view of the map (geographical center and zoom) performing a smooth pan-zoom animation.
flyToBounds( <LatLngBounds> bounds, <fitBounds options> options?) thisSets the view of the map with a smooth animation like flyTo, but takes a bounds parameter like fitBounds.
setLang( <String> lang )String {/* TODO: translation */}

Other Methods

MethodReturnsDescription
addHandler( <String> name, <Function> HandlerClass) thisAdds a new Handler to the map, given its name and constructor function.
remove()thisDestroys the map and clears all related event listeners.
createPane( <String> name, <HTMLElement> container?) HTMLElementCreates a new map pane with the given name if it doesn't exist already, then returns it. The pane is created as a children of container, or as a children of the main map pane if not set.
getPane(<String|HTMLElement> pane)HTMLElementReturns a map pane, given its name or its HTML element (its identity).
getPanes()ObjectReturns a plain object containing the names of all panes as keys and the panes as values.
getContainer()HTMLElementReturns the HTML element that contains the map.
whenReady( <Function> fn, <Object> context?) thisRuns the given function fn when the map gets initialized with a view (center and zoom) and at least one layer, or immediately if it's already initialized, optionally passing a function context.

Methods for Getting Map State

MethodReturnsDescription
getCenter()LatLngReturns the geographical center of the map view
getZoom()NumberReturns the current zoom level of the map view
getBounds()LatLngBoundsReturns the geographical bounds visible in the current map view
getMinZoom()NumberReturns the minimum zoom level of the map (if set in the minZoom option of the map or of any layers), or 0 by default.
getMaxZoom()NumberReturns the maximum zoom level of the map (if set in the maxZoom option of the map or of any layers).
getBoundsZoom( <LatLngBounds> bounds, <Boolean> inside?) NumberReturns the maximum zoom level on which the given bounds fit to the map view in its entirety. If inside (optional) is set to true, the method instead returns the minimum zoom level on which the map view fits into the given bounds in its entirety.
getSize()PointReturns the current size of the map container (in pixels).
getPixelBounds()BoundsReturns the bounds of the current map view in projected pixel coordinates (sometimes useful in layer and overlay implementations).
getPixelOrigin()PointReturns the projected pixel coordinates of the top left point of the map layer (useful in custom layer and overlay implementations).
getPixelWorldBounds( <Number> zoom?) BoundsReturns the world's bounds in pixel coordinates for zoom level zoom. If zoom is omitted, the map's current zoom level is used.
getLang()String{/* TODO: translation */}

Conversion Methods

MethodReturnsDescription
getZoomScale( <Number> toZoom, <Number> fromZoom) NumberReturns the scale factor to be applied to a map transition from zoom level fromZoom to toZoom. Used internally to help with zoom animations.
getScaleZoom( <Number> scale, <Number> fromZoom) NumberReturns the zoom level that the map would end up at, if it is at fromZoom level and everything is scaled by a factor of scale. Inverse of getZoomScale.
project( <LatLng> latlng, <Number> zoom) PointProjects a geographical coordinate LatLng according to the projection of the map's CRS, then scales it according to zoom and the CRS's Transformation. The result is pixel coordinate relative to the CRS origin.
unproject( <Point> point, <Number> zoom) LatLngInverse of project.
layerPointToLatLng( <Point> point) LatLngGiven a pixel coordinate relative to the origin pixel, returns the corresponding geographical coordinate (for the current zoom level).
latLngToLayerPoint( <LatLng> latlng) PointGiven a geographical coordinate, returns the corresponding pixel coordinate relative to the origin pixel.
wrapLatLng( <LatLng> latlng) LatLngReturns a LatLng where lat and lng has been wrapped according to the map's CRS's wrapLat and wrapLng properties, if they are outside the CRS's bounds. By default this means longitude is wrapped around the dateline so its value is between -180 and +180 degrees.
distance( <LatLng> latlng1, <LatLng> latlng2) NumberReturns the distance between two geographical coordinates according to the map's CRS. By default this measures distance in meters.
containerPointToLayerPoint( <Point> point) PointGiven a pixel coordinate relative to the map container, returns the corresponding pixel coordinate relative to the origin pixel.
layerPointToContainerPoint( <Point> point) PointGiven a pixel coordinate relative to the origin pixel, returns the corresponding pixel coordinate relative to the map container.
containerPointToLatLng( <Point> point) PointGiven a pixel coordinate relative to the map container, returns the corresponding geographical coordinate (for the current zoom level).
latLngToContainerPoint( <LatLng> latlng) PointGiven a geographical coordinate, returns the corresponding pixel coordinate relative to the map container.
mouseEventToContainerPoint( <MouseEvent> ev) PointGiven a MouseEvent object, returns the pixel coordinate relative to the map container where the event took place.
mouseEventToLayerPoint( <MouseEvent> ev) PointGiven a MouseEvent object, returns the pixel coordinate relative to the origin pixel where the event took place.
mouseEventToLatLng( <MouseEvent> ev) LatLngGiven a MouseEvent object, returns geographical coordinate where the event took place.

Geolocation methods

MethodReturnsDescription
locate( <Locate options> options?) thisTries to locate the user using the Geolocation API, firing a locationfound event with location data on success or a locationerror event on failure, and optionally sets the map view to the user's location with respect to detection accuracy (or to the world view if geolocation failed). See Locate options for more details.
stopLocate()thisStops watching location previously initiated by map.locate({watch: true}) and aborts resetting the map view if map.locate was called with {setView: true}.

Methods inherited from Evented

Methods inherited from Evented see here.

Properties

Handlers

PropertyTypeDescription
boxZoomHandlerBox (shift-drag with mouse) zoom handler.
doubleClickZoomHandlerDouble click zoom handler.
draggingHandlerMap dragging handler (by both mouse and touch).
keyboardHandlerKeyboard navigation handler.
scrollWheelZoomHandlerScroll wheel zoom handler.
tapHandlerMobile touch hacks (quick tap and touch hold) handler.
touchZoomHandlerTouch zoom handler.
geoclickerHandler{/* TODO: translation */}
projectDetectorHandler{/* TODO: translation */}
zoomControlControl.Zoom{/* TODO: translation */}
fullscreenControlControl.FullScreen{/* TODO: translation */}
rulerControlControl.Ruler{/* TODO: translation */}
trafficControlControl.Traffic{/* TODO: translation */}
baseLayerTileLayer{/* TODO: translation */}

Map panes

Panes are DOM elements used to control the ordering of layers on the map. You can access panes with map.getPane or map.getPanes methods. New panes can be created with the map.createPane method. Every map has the following default panes that differ only in zIndex.

PaneTypeZ-indexDescription
mapPaneHTMLElement 'auto'Pane that contains all other map panes
tilePaneHTMLElement 2Pane for tile layers
overlayPaneHTMLElement 4Pane for overlays like polylines and polygons
shadowPaneHTMLElement 5Pane for overlay shadows (e.g. marker shadows)
markerPaneHTMLElement 6Pane for marker icons
popupPaneHTMLElement 7Pane for popups.

Locate options

Some of the geolocation methods for Map take in an options parameter. This is a plain javascript object with the following optional components:

OptionTypeDefaultDescription
watchBoolean falseIf true, starts continous watching of location changes (instead of detecting it once) using W3C watchPosition method. You can later stop watching using map.stopLocate() method.
setViewBoolean falseIf true, automatically sets the map view to the user location with respect to detection accuracy, or to world view if geolocation failed.
maxZoomNumber InfinityThe maximum zoom for automatic view setting when using setView option.
timeoutNumber 10000Number of milliseconds to wait for a response from geolocation before firing a locationerror event.
maximumAgeNumber 0Maximum age of detected location. If less than this amount of milliseconds passed since last geolocation response, locate will return a cached location.
enableHighAccuracyBoolean falseEnables high accuracy, see description in the W3C spec.

Zoom options

Some of the Map methods which modify the zoom level take in an options parameter. This is a plain javascript object with the following optional components:

OptionTypeDefaultDescription
animateBooleanIf not specified, zoom animation will happen if the zoom origin is inside the current view. If true, the map will attempt animating zoom disregarding where zoom origin is. Setting false will make it always reset the view completely without animation.

Pan options

Some of the Map methods which modify the center of the map take in an options parameter. This is a plain javascript object with the following optional components:

OptionTypeDefaultDescription
animateBooleanIf true, panning will always be animated if possible. If false, it will not animate panning, either resetting the map view if panning more than a screen away, or just setting a new offset for the map pane (except for panBy which always does the latter).
durationNumber 0.25Duration of animated panning, in seconds.
easeLinearityNumber 0.25The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, the less the more bowed the curve.
noMoveStartBoolean falseIf true, panning won't fire movestart event on start (used internally for panning inertia).

Zoom/pan options

Options inherited from Zoom options

Options inherited from Pan options

FitBounds options

OptionTypeDefaultDescription
paddingTopLeftPoint [0, 0]Sets the amount of padding in the top left corner of a map container that shouldn't be accounted for when setting the view to fit bounds. Useful if you have some control overlays on the map like a sidebar and you don't want them to obscure objects you're zooming to.
paddingBottomRightPoint [0, 0]The same for the bottom right corner of the map.
paddingPoint [0, 0]Equivalent of setting both top left and bottom right padding to the same value.
maxZoomNumber nullThe maximum possible zoom to use.