MaplairMap extends Evented

The central class of the API — it is used to create a map on a page and manipulate it.

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.

Pane zIndex Description
mapPane 'auto' Pane that contains all other map panes
tilePane 200 Pane for GridLayers and TileLayers
overlayPane 400 Pane for vectors (Paths, like Polylines and Polygons), ImageOverlays and VideoOverlays
shadowPane 500 Pane for overlay shadows (e.g. Marker shadows)
markerPane 600 Pane for Icons of Markers
tooltipPane 650 Pane for Tooltips
popupPane 700 Pane for Popups

Map state change events

The map state change events movestart, move, moveend, zoomstart, zoom, zoomend and zoomanim caused by the user (e.g. dragging, scrolling, pinching, pressing a key or clicking a zoom button) have an originalEvent property with the DOM event that started the change. It is undefined for changes made by code (e.g. setView()), which allows to tell them apart, e.g. to avoid feedback loops when synchronizing the view. The move and zoom events also have flyTo: true on each flyTo animation frame, and pinch: true while the user pinch-zooms the map.

Usage example

// initialize the map on the "map" div with a given center and zoom
const map = new MaplairMap('map', {
	center: [51.505, -0.09],
	zoom: 13
});

Constructor

ConstructorDescription
new MaplairMap(id: string | HTMLElement, options?: MaplairMapOptions)

Instantiates a map object given the DOM ID of a <div> element or the element itself, and optionally an object literal with MaplairMap options.

id
The <div> element or its DOM ID.

Options

OptionTypeDefaultDescription
crsCRSEPSG3857

The Coordinate Reference System to use. Don't change this if you're not sure what it means.

centerLatLngExpression

Initial geographic center of the map.

zoomnumber

Initial map zoom level.

minZoomnumber

Minimum zoom level of the map. If not specified and at least one GridLayer or TileLayer is in the map, the lowest of their minZoom options will be used instead.

maxZoomnumber

Maximum zoom level of the map. If not specified and at least one GridLayer or TileLayer is in the map, the highest of their maxZoom options will be used instead.

layersLayer[][]

Array of layers that will be added to the map initially.

ariaLabelstring

The accessible name of the map, announced by screen readers, 'Map' by default. The map container gets the ARIA role region with this label, unless it already has a role or label. The default is translated, see I18n.

maxBoundsLatLngBoundsExpression

When this option is set, the map restricts the view to the given geographical bounds, bouncing the user back if the user 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. A new SVG renderer by default; pass new Canvas() to draw them on a canvas instead. Paths in custom panes get their own renderer for that pane, of the same class and with the same options as this one.

zoomAnimationbooleantrue

Whether the map zoom animation is enabled.

zoomAnimationThresholdnumber4

Won't animate zoom if the zoom difference exceeds this value (or 1 if the user prefers reduced motion and animate: true isn't passed).

continuousZoombooleanfalse

Whether zoom animations (e.g. of the zoom control, double click and keyboard) change the view frame by frame through fractional zoom levels, like flyTo() and pinch zoom, instead of scaling the map with a CSS transition between two zoom levels. Also makes the scroll wheel zoom smoothly with each wheel event (see scrollWheelZoom), snapping to zoomSnap when scrolling ends.

fadeAnimationbooleantrue

Whether the tile and popup fade animation is enabled.

markerZoomAnimationbooleantrue

Whether markers animate their zoom with the zoom animation, if disabled they will disappear for the length of the animation.

markerCullingbooleanfalse

Whether markers far outside of the map view (more than half a view away) are taken off the page until the map is moved closer to them. This reduces the browser's rendering work, and the work of repositioning markers while zooming, when a map has many markers (e.g. several thousands) of which only some are visible at a time.

transform3DLimitnumber8388608

Defines the maximum size of a CSS translation transform (2^23). The default value should not be changed unless a web browser positions layers in the wrong place after doing a large panBy.

zoomSnapnumber1

Forces 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.

zoomDeltanumber1

Controls 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.

trackResizebooleantrue

Whether the map automatically handles browser window resize to update itself. A hidden map (with the size 0, e.g. display: none in an inactive tab) keeps its size, view and bounds until it is shown again.

attributionControlbooleantrue

Whether a attribution control is added to the map by default.

fullscreenControlbooleanfalse

Whether a fullscreen control is added to the map by default.

rotateControlbooleanfalse

Whether a rotate control is added to the map by default.

zoomControlbooleantrue

Whether a zoom control is added to the map by default.

closePopupOnClickbooleantrue

Set it to false if you don't want popups to close when user clicks the map.

rendererRenderer

The default method for drawing vector layers on the map. A new SVG renderer by default; pass new Canvas() to draw them on a canvas instead. Paths in custom panes get their own renderer for that pane, of the same class and with the same options as this one.

bearingnumber0

Initial rotation of the map in degrees: the compass direction pointing up, clockwise from north (e.g. 90 for east up), see setBearing().

Added by the optional module maplair/map-rotation.

pinchRotatebooleanfalse

Whether the map can be rotated by turning two fingers, see setBearing().

Added by the optional module maplair/map-rotation.

boxZoombooleantrue

Whether the map can be zoomed to a rectangular area specified by dragging the pointer while pressing the shift key.

displaceboolean|DisplaceHandlerOptions

Whether to displace overlapping CircleMarkers, either true or an object overriding the options of DisplaceHandler. Needs the DisplaceHandler to be added to the map, see there.

doubleClickZoomboolean|'center'true

Whether 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 pointer was.

draggingbooleantrue

Whether the map is draggable with pointer or not.

inertiabooleantrue

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.

inertiaDecelerationnumber3400

The rate with which the inertial movement slows down, in pixels/second².

inertiaMaxSpeednumber1400

Max speed of the inertial movement, in pixels/second.

easeLinearitynumber0.2

The linearity of the easing of the inertial movement.

worldCopyJumpbooleanfalse

With 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. A map with an infinite CRS, such as SimpleCRS, does not jump, as it has no copies of the world.

maxBoundsViscositynumber0.0

If 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.

keyboardbooleantrue

Makes the map focusable and allows users to navigate the map with keyboard arrows and +/- keys.

keyboardPanDeltanumber80

Amount of pixels to pan when pressing an arrow key.

ariaKeyShortcutsboolean|stringfalse

Sets the aria-keyshortcuts attribute of the map container. ARIA names keys by what they type on a given layout, so true uses the names for a US English layout, which can be wrong for pages in other languages; pass a string to set the value for your audience's layout instead.

pinchZoomboolean|'center'true

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.

bounceAtZoomLimitsbooleantrue

Set it to false if you don't want the map to zoom beyond min/max zoom and then bounce back when pinch-zooming.

touchZoomboolean|'center'

Deprecated, use pinchZoom instead.

scrollWheelZoomboolean|'center'|'trackpad'true

Whether the map can be zoomed by using the mouse wheel and by pinching on a touchpad (or using the mouse wheel with the Ctrl key). If passed 'center', it will zoom to the center of the view regardless of where the pointer was. If passed 'trackpad', scrolling (e.g. with two fingers on a touchpad) pans the map instead, while pinching still zooms.

wheelDebounceTimenumber40

Limits the rate at which a wheel can fire (in milliseconds). By default, the user can't zoom via wheel more often than once per 40 ms.

wheelPxPerZoomLevelnumber60

How many scroll pixels (as reported by DomEvent.getWheelDelta) mean a change of one full zoom level. Smaller values will make wheel-zooming faster (and vice versa).

tapDragZoomboolean|'center'true

Whether the map can be zoomed with one finger by tapping once, then touching again and dragging down (zoom in) or up (zoom out). If passed 'center', it will zoom to the center of the view regardless of where the finger was.

tapHoldbooleantrue

Enables simulation of contextmenu event on touch and hold.

tapTolerancenumber15

The max number of pixels a user can shift his finger during touch for it to be considered a valid tap.

Events

EventDataDescription
baselayerchangeLayersControlEventFired when the base layer is changed through the layers control.
overlayaddLayersControlEventFired when an overlay is selected through the layers control.
overlayremoveLayersControlEventFired when an overlay is deselected through the layers control.
searchresultSearchResultEventFired when a result of the search control is selected.
dividermoveDividerMoveEventFired when the divider of a SideBySideControl moves.
timechangeTimeChangeEventFired when the current time of a TimeControl changes.
resizeResizeEventFired when the map is resized.
unloadMaplairEventFired when the map is destroyed with remove method.
viewpreresetMaplairEventFired before the map resets its view (see viewreset).
viewresetMaplairEventFired when the map needs to redraw its content (this usually happens on map zoom or load). Very useful for creating custom overlays.
loadMaplairEventFired when the map is initialized (when its center and zoom are set for the first time).
zoomstartMaplairEventFired when the map zoom is about to change (e.g. before zoom animation).
movestartMaplairEventFired when the view of the map starts changing (e.g. user starts dragging the map).
zoomMaplairEventFired repeatedly during any change in zoom level, including zoom and fly animations.
moveMaplairEventFired repeatedly during any movement of the map, including pan and fly animations.
zoomendMaplairEventFired when the map zoom changed, after any animations.
moveendMaplairEventFired when the center of the map stops changing (e.g. user stopped dragging the map or after non-centered zoom).
idleMaplairEventFired when the map becomes idle: the view is not changing (no dragging, panning or zooming, including their animations) and all layers have finished loading (e.g. the tiles of tile layers, see GridLayer.isLoading()). Useful e.g. for taking screenshots or for tests.
locationerrorMaplairErrorEventFired when geolocation (using the locate method) failed.
locationfoundLocationEventFired when geolocation (using the locate method) went successfully.
clickMaplairPointerEventFired when the user clicks (or taps) the map.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the map.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the map.
pointerupMaplairPointerEventFired when the user releases the pointer on the map.
pointeroverMaplairPointerEventFired when the pointer enters the map.
pointeroutMaplairPointerEventFired when the pointer leaves the map.
pointermoveMaplairPointerEventFired while the pointer moves over the map.
contextmenuMaplairPointerEventFired 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).
preclickMaplairPointerEventFired before pointer click on the map (sometimes useful when you want something to happen on click before any existing click handlers start running).
keydownMaplairKeyboardEventFired when the user presses a key from the keyboard while the map is focused.
keyupMaplairKeyboardEventFired when the user releases a key from the keyboard while the map is focused.
crschangeCrsChangeEventFired when the CRS of the map changes with setCrs(), before the view is reset.
worldcopyjumpWorldCopyJumpEventFired when worldCopyJump moves the map pane by one or more world widths.
pixelratiochangeMaplairEventFired when the devicePixelRatio of the browser changes, e.g. when moving the window to a screen with another resolution or when zooming the page. Tile layers with detectRetina and canvas renderers adapt to it.
zoomanimZoomAnimEventFired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom.
boxzoomstartMaplairEventFired when the user starts drawing a box to zoom to.
boxzoomendBoxZoomEndEventFired when the user has drawn a box and the map is zoomed to it.
dragstartMaplairEventFired when the user starts dragging the map.
dragMaplairEventFired repeatedly while the user drags the map.
dragendDragEndEventFired when the user stops dragging the map.
focusMaplairEventFired when the map gains focus.
blurMaplairEventFired when the map loses focus.
enterfullscreenMaplairEventFired when the map enters fullscreen.
exitfullscreenMaplairEventFired when the map exits fullscreen.
fullscreenchangeMaplairEventFired when the map enters or exits fullscreen.
layeraddLayerEventFired when a new layer is added to the map.
layerremoveLayerEventFired when some layer is removed from the map.
zoomlevelschangeMaplairEventFired when the number of zoomlevels on the map is changed due to adding or removing a layer.
popupopenPopupEventFired when a popup is opened in the map.
popupclosePopupEventFired when a popup in the map is closed.
autopanstartMaplairEventFired when the map starts autopanning when opening a popup.
tooltipopenTooltipEventFired when a tooltip is opened in the map.
tooltipcloseTooltipEventFired when a tooltip in the map is closed.
rotateMaplairEventFired when the bearing of the map changes, see setBearing(). (maplair/map-rotation)

Methods

Methods for modifying map state

MethodReturnsDescription
setView(center: LatLngExpression, zoom?: number, options?: ZoomPanOptions)this

Sets the view of the map (geographical center and zoom) with the given animation options.

setZoom(zoom: number, options?: ZoomPanOptions)this

Sets the zoom of the map.

zoomIn(delta?: number, options?: ZoomOptions)this

Increases the zoom of the map by delta (zoomDelta by default).

zoomOut(delta?: number, options?: ZoomOptions)this

Decreases the zoom of the map by delta (zoomDelta by default).

setZoomAround(latlng: LatLngExpression | Point, zoom: number, options?: ZoomOptions)this

Zooms the map while keeping a specified geographical point on the map stationary (e.g. used internally for scroll zoom and double-click zoom). Given a Point, it keeps the specified pixel on the map (relative to the top-left corner) stationary instead.

latlng
The geographical point or the pixel offset.
fitBounds(bounds: LatLngBoundsExpression, options?: FitBoundsOptions)this

Sets a map view that contains the given geographical bounds with the maximum zoom level possible.

fitWorld(options?: FitBoundsOptions)this

Sets a map view that mostly contains the whole world with the maximum zoom level possible.

panTo(center: LatLngExpression, options?: PanOptions)this

Pans the map to a given center.

panBy(offset: PointExpression, options?: PanOptions)this

Pans the map by a given number of pixels (animated unless animate: false is passed, or the user prefers reduced motion and the pan is longer than half the map size without animate: true).

flyTo(targetCenter: LatLngExpression, targetZoom?: number, options?: ZoomPanOptions)this

Sets the view of the map (geographical center and zoom) performing a smooth pan-zoom animation. If the user prefers reduced motion (and animate: true isn't passed), it behaves like setView instead, only animating short pans and zooms.

flyToBounds(bounds: LatLngBoundsExpression, options?: FitBoundsOptions)this

Sets the view of the map with a smooth animation like flyTo, but takes a bounds parameter like fitBounds.

setCrs(crs: CRS)this

Changes the Coordinate Reference System of the map, keeping its center and (as far as possible with the zoom levels and zoomSnap) its scale at the center. All layers are redrawn in the new CRS; note that tile layers only work with the CRS their tiles were made for.

setMaxBounds(bounds: LatLngBoundsExpression)this

Restricts the map view to the given bounds (see the maxBounds option).

setMinZoom(zoom: number)this

Sets the lower limit for the available zoom levels (see the minZoom option).

setMaxZoom(zoom: number)this

Sets the upper limit for the available zoom levels (see the maxZoom option).

panInsideBounds(bounds: LatLngBoundsExpression, options?: PanOptions)this

Pans 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.

panInside(latlng: LatLngExpression, options?: PaddingOptions & PanOptions)this

Pans the map the minimum amount to make the latlng visible. Use padding options to fit the display to more restricted bounds. If latlng is already within the (optionally padded) display bounds, the map will not be panned.

invalidateSize(options?: InvalidateSizeOptions | boolean)this

Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also panning to keep the center 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. Passing true instead of options animates the panning.

stop()this

Stops the currently running panTo or flyTo animation, if any.

toggleFullscreen()this

Enters or exits the fullscreen view of the map, see FullscreenControl. Browsers allow entering fullscreen only in response to a user interaction, e.g. a click.

Geolocation methods

MethodReturnsDescription
locate(options?: LocateOptions)this

Tries 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). Note that, if your page doesn't use HTTPS, this method will fail in modern browsers (Chrome 50 and newer) See LocateOptions for more details.

stopLocate()this

Stops watching location previously initiated by map.locate({watch: true}) and aborts resetting the map view if map.locate was called with {setView: true}.

Methods for getting map state

MethodReturnsDescription
getCenter()LatLng

Returns the geographical center of the map view.

getZoom()number

Returns the current zoom level of the map view.

getBounds()LatLngBounds

Returns the geographical bounds visible in the current map view.

getMinZoom()number

Returns 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()number

Returns the maximum zoom level of the map (if set in the maxZoom option of the map or of any layers).

getBoundsZoom(bounds: LatLngBoundsExpression, inside?: boolean, padding?: PointExpression)number

Returns 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()Point

Returns the current size of the map container (in pixels).

getPixelBounds(center?: LatLngExpression, zoom?: number)Bounds

Returns the bounds of the current map view in projected pixel coordinates (sometimes useful in layer and overlay implementations). If center and zoom is omitted, the map's current zoom level and center is used.

getPixelOrigin()Point

Returns the projected pixel coordinates of the top left point of the map layer (useful in custom layer and overlay implementations).

getPixelWorldBounds(zoom?: number)Bounds | null

Returns the world's bounds in pixel coordinates for zoom level zoom. If zoom is omitted, the map's current zoom level is used.

Returns null for CRSs with infinite bounds.

Conversion methods

MethodReturnsDescription
getZoomScale(toZoom: number, fromZoom?: number)number

Returns the scale factor to be applied to a map transition from zoom level fromZoom to toZoom. Used internally to help with zoom animations.

getScaleZoom(scale: number, fromZoom?: number)number

Returns 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: LatLngExpression, zoom?: number)Point

Projects 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: PointExpression, zoom?: number)LatLng

Inverse of project.

layerPointToLatLng(point: PointExpression)LatLng

Given a pixel coordinate relative to the origin pixel, returns the corresponding geographical coordinate (for the current zoom level).

latLngToLayerPoint(latlng: LatLngExpression)Point

Given a geographical coordinate, returns the corresponding pixel coordinate relative to the origin pixel.

wrapLatLng(latlng: LatLngExpression)LatLng

Returns 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.

wrapLatLngBounds(bounds: LatLngBoundsExpression)LatLngBounds

Returns a LatLngBounds with the same size as the given one, ensuring that its center is within the CRS's bounds. By default this means the center longitude is wrapped around the dateline so its value is between -180 and +180 degrees, and the majority of the bounds overlaps the CRS's bounds.

distance(latlng1: LatLngExpression, latlng2: LatLngExpression)number

Returns the distance between two geographical coordinates according to the map's CRS. By default this measures distance in meters.

containerPointToLayerPoint(point: PointExpression)Point

Given a pixel coordinate relative to the map container, returns the corresponding pixel coordinate relative to the origin pixel.

layerPointToContainerPoint(point: PointExpression)Point

Given a pixel coordinate relative to the origin pixel, returns the corresponding pixel coordinate relative to the map container.

containerPointToLatLng(point: PointExpression)LatLng

Given a pixel coordinate relative to the map container, returns the corresponding geographical coordinate (for the current zoom level).

latLngToContainerPoint(latlng: LatLngExpression)Point

Given a geographical coordinate, returns the corresponding pixel coordinate relative to the map container.

pointerEventToContainerPoint(e: MouseEvent | PointerEvent)Point

Given a PointerEvent object, returns the pixel coordinate relative to the map container where the event took place.

pointerEventToLayerPoint(e: MouseEvent | PointerEvent)Point

Given a PointerEvent object, returns the pixel coordinate relative to the origin pixel where the event took place.

pointerEventToLatLng(e: MouseEvent | PointerEvent)LatLng

Given a PointerEvent object, returns geographical coordinate where the event took place.

Methods for layers and controls

MethodReturnsDescription
addControl(control: Control)this

Adds the given control to the map.

removeControl(control: Control)this

Removes the given control from the map.

addLayer(layer: Layer)this

Adds the given layer to the map.

removeLayer(layer: Layer)this

Removes the given layer from the map.

hasLayer(layer: Layer)boolean

Returns true if the given layer is currently added to the map.

eachLayer(method: (layer: Layer) => void, context?: object)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 | DivOverlayContent, latlng?: LatLngExpression, options?: PopupOptions)this

Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability).

Alternatively, creates a popup with the specified content and options and opens it in the given point on a map. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

popup
The popup, or the content of a new popup.
closePopup(popup?: Popup, …args: any[])this

Closes the popup previously opened with openPopup (or the given one).

openTooltip(tooltip: Tooltip | DivOverlayContent, latlng?: LatLngExpression, options?: TooltipOptions)this

Opens the specified tooltip.

Alternatively, creates a tooltip with the specified content and options and opens it. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

tooltip
The tooltip, or the content of a new tooltip.
closeTooltip(tooltip: Tooltip)this

Closes the tooltip given as parameter.

Map rotation

MethodReturnsDescription
setBearing(bearing: number, options?: { animate?: boolean; })this

Rotates the map around the center of the view, so that the compass direction bearing (in degrees, clockwise from north) points up. Markers, popups and tooltips stay upright. With {animate: true}, the map rotates smoothly (the shorter way round).

Added by the optional module maplair/map-rotation.

getBearing()number

Returns the rotation of the map, see setBearing().

Added by the optional module maplair/map-rotation.

Other methods

MethodReturnsDescription
addHandler(name: string, HandlerClass: new (map: MaplairMap) => Handler)this

Adds a new Handler to the map, given its name and constructor function.

remove()this

Destroys the map and clears all related event listeners.

createPane(name: string, container?: HTMLElement)HTMLElement

Creates a new map pane with the given name if it doesn't exist already, then returns it. The pane is created as a child of container, or as a child of the main map pane if not set.

getPane(pane: string | HTMLElement)HTMLElement

Returns a map pane, given its name or its HTML element (its identity).

getPanes()Record<string, HTMLElement>

Returns a plain object containing the names of all panes as keys and the panes as values.

getContainer()HTMLElement

Returns the HTML element that contains the map.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type, see Evented.fire(). The map state change events caused by the user get an originalEvent property (see the class description).

whenReady(callback: (event: { target: MaplairMap; }) => void, context?: object)this

Runs the given function callback 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.

isFullscreen()boolean

Returns true if the map is viewed in fullscreen.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Properties

PropertyTypeDescription
attributionControlAttributionControl

The attribution control of the map, the default one (if the attributionControl option was true when creating the map) or the one added last.

fullscreenControlFullscreenControl

The default fullscreen control (only available if the fullscreenControl option was true when creating the map).

rotateControlRotateControl

The default rotate control (only available if the rotateControl option was true when creating the map).

zoomControlZoomControl

The default zoom control (only available if the zoomControl option was true when creating the map).

boxZoomBoxZoomHandler

Box (shift-drag with pointer) zoom handler.

displaceDisplaceHandler

The displacement handler, if added with the name displace.

doubleClickZoomDoubleClickZoomHandler

Double click zoom handler.

draggingDragHandler

Map dragging handler.

keyboardKeyboardHandler

Keyboard navigation handler.

pinchZoomPinchZoomHandler

Pinch zoom handler.

touchZoomPinchZoomHandler

Deprecated, the same as pinchZoom.

scrollWheelZoomScrollWheelZoomHandler

Scroll wheel zoom handler.

tapDragZoomTapDragZoomHandler

Tap-drag zoom handler (double tap and drag with one finger).

tapHoldTapHoldHandler

Long tap handler to simulate contextmenu event (useful in mobile Safari).

Hash

Keeps the view of the map in the hash of the URL, e.g. #13/47.2692/11.4041 (zoom, latitude, longitude, and the bearing of a rotated map) or as geo URI #geo:47.2692,11.4041?z=13 (see the format option), so that it can be bookmarked and shared. The view is restored from the hash (in either format) when creating the Hash and when the hash changes (e.g. with the back button of the browser).

With the layers option, the hash also keeps the base layer and the overlays shown on the map, e.g. #13/47.2692/11.4041?layers=OSM,Bike%20routes.

With the option mode: 'query', the view is kept in the query string instead, e.g. ?zoom=13&lat=47.2692&lng=11.4041, keeping the other parameters of the app.

Inspired by the leaflet-hash plugin.

Usage example

const map = new MaplairMap('map').setView([47.27, 11.40], 13);
new Hash(map);

// with the layers of a layers control
const baseLayers = {OSM: osm, Topo: topo}, overlays = {'Bike routes': bikes};
new LayersControl(baseLayers, overlays).addTo(map);
new Hash(map, {layers: {...baseLayers, ...overlays}});

// in the query string, e.g. ?q=cafe&zoom=13&lat=47.2692&lng=11.4041
new Hash(map, {mode: 'query'});

Constructor

ConstructorDescription
new Hash(map: MaplairMap, options?: HashOptions)

Synchronizes the view of map with the hash of the URL.

Options

OptionTypeDefaultDescription
format'zoom/lat/lng'|'geo''zoom/lat/lng'

The format of the hash: 'zoom/lat/lng' for #13/47.2692/11.4041, or 'geo' for a geo URI with the zoom as parameter z like in Android, #geo:47.2692,11.4041?z=13. The bearing of a rotated map is added as fourth number or parameter bearing.

layersRecord<string, Layer>

The layers to keep in the hash by name, e.g. the base layers and overlays of a LayersControl: the names of those on the map are added as parameter layers, and restoring the hash adds the named layers to the map and removes the others.

mode'hash'|'query''hash'

Where to keep the view: 'hash' for the hash of the URL, or 'query' for the parameters zoom, lat, lng, bearing (of a rotated map) and layers of the query string (the format option is ignored), keeping the other parameters, e.g. ?q=cafe&zoom=13&lat=47.2692&lng=11.4041. The view is restored on navigating in the history of the browser (popstate).

Methods

MethodReturnsDescription
remove()this

Stops synchronizing the view with the hash of the URL.

Static members

MethodReturnsDescription
parse(hash: string)HashView | undefined

Parses a hash like #13/47.2692/11.4041[/30][?layers=A,B] or #geo:47.2692,11.4041[?z=13][&layers=A,B] to an object with the center (LatLng), the zoom (if any), the optional bearing and the names of the layers (if any), or returns undefined for other hashes.

format(map: MaplairMap, format?: "zoom/lat/lng" | "geo", layers?: Record<string, Layer>)string

Returns the hash for the view of the map in the given format (see the options), with as many decimal places of the coordinates as needed for the precision of a pixel, and the names of the given layers on the map.

parseQuery(search: string)HashView | undefined

Parses the parameters zoom, lat, lng, bearing and layers of a query string like ?q=cafe&zoom=13&lat=47.2692&lng=11.4041 like parse(), or returns undefined without lat and lng.

formatQuery(map: MaplairMap, layers?: Record<string, Layer>, search?: string)string

Returns the query string search with the parameters for the view of the map (see format()) instead of the previous ones, keeping the other parameters.

MapSync

Synchronizes the views (center, zoom and bearing) of several maps, e.g. to compare different layers side by side: whenever one of the maps moves (by the user or by code, including animations), the other maps follow.

With the options oneWay and fit: 'bounds', smaller maps can follow a main map showing its bounds, e.g. thumbnails next to it.

Inspired by the Leaflet.Sync plugin.

Usage example

const sync = new MapSync([map1, map2]);
// later
sync.remove();

// a thumbnail showing the bounds of the main map
new MapSync([map, thumbnail], {oneWay: true, fit: 'bounds'});

Constructor

ConstructorDescription
new MapSync(maps: MaplairMap[], options?: MapSyncOptions)

Synchronizes the views of the given maps, starting with the view of the first map.

Options

OptionTypeDefaultDescription
bearingbooleantrue

Whether to synchronize the bearing of rotated maps (with the map rotation, see MaplairMap.setBearing()).

oneWaybooleanfalse

Whether only the first map leads and the other maps follow it, without moving the first map when they are moved.

fit'center'|'bounds''center'

How the maps follow: 'center' with the same center and zoom, or 'bounds' with the same center, zoomed so that the bounds of the leading map fit (like fitBounds()), for maps of different sizes.

Methods

MethodReturnsDescription
remove()this

Stops synchronizing the maps.

Marker extends Layer

Marker is used to display clickable/draggable icons on the map. Extends Layer.

In addition to shared layer methods like addTo() and remove() and popup methods like bindPopup() you can also use the methods below.

Usage example

new Marker([50.5, 30.5]).addTo(map);

Constructor

ConstructorDescription
new Marker(latlng: LatLngExpression, options?: MarkerOptions)

Instantiates a Marker object given a geographical point and optionally an options object.

Options

OptionTypeDefaultDescription
iconIconnew DefaultIcon()

Icon instance to use for rendering the marker. See Icon documentation for details on how to customize the marker icon. If not specified, a common instance of DefaultIcon is used.

keyboardbooleantrue

Whether the marker can be tabbed to with a keyboard and, if interactive, clicked by pressing Enter or Space.

titlestring''

Text for the browser tooltip that appear on marker hover (no tooltip by default). Useful for accessibility.

altstring

Text for the alt attribute of the icon image, the translation of 'Marker' by default. Useful for accessibility.

zIndexOffsetnumber0

By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like 1000 (or high negative value, respectively).

opacitynumber1

The opacity of the marker.

rotationnumber|nullnull

Rotation of the marker icon in degrees, clockwise, around the icon anchor, e.g. for the heading of a vehicle. A rotated marker, even at 0°, has no shadow, since the shadow of an upright pin looks wrong under a tilted one. null means no rotation.

riseOnHoverbooleanfalse

If true, the marker will get on top of others while the pointer is over it. It always does while it has focus.

riseOffsetnumber250

The z-index offset used when the marker gets on top of others on hover or focus.

panestring'markerPane'

Map pane where the markers icon will be added.

shadowPanestring'shadowPane'

Map pane where the markers shadow will be added.

shadowbooleantrue

Whether to show the shadow of the marker's icon. Each shadow is an additional element on the page, so disabling shadows noticeably reduces the browser's rendering work when showing many markers (e.g. several thousands), especially while panning and zooming. To disable shadows for all markers, use Marker.mergeOptions({shadow: false}).

bubblingPointerEventsbooleanfalse

When true, a pointer event on this marker will trigger the same event on the map (unless DomEvent.stopPropagation is used).

autoPanOnFocusbooleantrue

When true, the map will pan whenever the marker is focused (via e.g. pressing tab on the keyboard) to ensure the marker is visible within the map's bounds.

draggablebooleanfalse

Whether the marker is draggable with pointer or not. A focused draggable marker can also be moved with the arrow keys, by 10 pixels or 30 with Shift.

autoPanbooleanfalse

Whether to pan the map when dragging this marker near its edge or not.

autoPanPaddingPointExpression[50, 50]

Distance (in pixels to the left/right and to the top/bottom) of the map edge to start panning the map.

autoPanSpeednumber10

Number of pixels the map should pan by.

rotateWithViewbooleanfalse

On a rotated map (see MaplairMap.setBearing()), whether the icon rotates with the map (e.g. for arrows pointing in a geographic direction) instead of staying upright. The rotation of the marker is relative to the screen, or to north with rotateWithView.

Added by the optional module maplair/map-rotation.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
dragstartMaplairEventFired when the user starts dragging the marker.
movestartMaplairEventFired when the marker starts moving (because of dragging).
dragMarkerMoveEventFired repeatedly while the user drags the marker.
dragendDragEndEventFired when the user stops dragging the marker.
moveendMaplairEventFired when the marker stops moving (because of dragging).
moveMarkerMoveEventFired when the marker is moved via setLatLng or by dragging. Old and new coordinates are included in event arguments as oldLatLng, latlng.
moveendMaplairEventFired when the marker stops moving (after dragging or moveAlong()). (maplair/marker-movement)
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Marker movement

MethodReturnsDescription
moveTo(latlng: LatLngExpression, options?: MarkerMovementOptions)this

Moves the marker smoothly to latlng, see moveAlong().

Added by the optional module maplair/marker-movement.

moveAlong(latlngs: LatLngExpression[], options?: MarkerMovementOptions)this

Moves the marker smoothly along the given points, frame by frame at a constant speed, e.g. to follow a vehicle or to replay a track. Fires move with each frame and moveend at the end. A new movement or stopMoving() stops it; with reduced motion, the marker jumps to the end. Inspired by the Leaflet.MovingMarker and Leaflet.AnimatedMarker plugins.

Added by the optional module maplair/marker-movement.

stopMoving()this

Stops the movement of moveTo() or moveAlong().

Added by the optional module maplair/marker-movement.

isMoving()boolean

Returns true while the marker moves with moveTo() or moveAlong().

Added by the optional module maplair/marker-movement.

Other methods

MethodReturnsDescription
onAdd(map: MaplairMap)void

Adds the icon (and shadow) of the marker to the map.

onRemove(map: MaplairMap)void

Removes the icon (and shadow) of the marker from the map.

getEvents()Record<string, Function>

Returns the map events the marker listens to, see Layer.

getLatLng()LatLng

Returns the current geographical position of the marker.

setLatLng(latlng: LatLngExpression)this

Changes the marker position to the given point.

setZIndexOffset(offset: number)this

Changes the zIndex offset of the marker.

getIcon()Icon

Returns the current icon used by the marker.

setIcon(icon: Icon)this

Changes the marker icon.

getElement()HTMLElement

Returns the instance of HTMLElement used by Marker layer.

update()this

Updates the position of the marker on the map, e.g. after a change of its options.

getRotation()number | null

Returns the current rotation of the marker in degrees.

setRotation(rotation: number | null)this

Changes the rotation of the marker; null removes it.

setOpacity(opacity: number)this

Changes the opacity of the marker.

toGeoJSON(precision?: number | false)Feature

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the marker (as a GeoJSON Point Feature).

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Properties

PropertyTypeDescription
draggingMarkerDrag | undefined

Marker dragging handler, see Handler. Only valid when the marker is on the map (otherwise set marker.options.draggable).

Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see Handler methods). Example:

marker.dragging.disable();

DivOverlay extends Layer

Base model for Popup and Tooltip; use those to show content on the map. Inherit from it for custom overlays like plugins.

Constructor

ConstructorDescription
new DivOverlay(options?: DivOverlayOptions | undefined, source?: Layer | undefined)

Instantiates an overlay given an optional options object that describes its appearance and location and an optional source object that is used to tag the overlay with a reference to the Layer to which it refers.

new DivOverlay(latlng: LatLngExpression, options?: DivOverlayOptions | undefined)

Instantiates an overlay given latlng where the overlay will open and an optional options object that describes its appearance and location.

Options

OptionTypeDefaultDescription
interactivebooleanfalse

If true, the popup/tooltip will listen to the pointer events.

offsetPointExpression[0, 0]

The offset of the overlay position.

classNamestring''

A custom CSS class name to assign to the overlay.

panestring

Map pane where the overlay will be added.

overflowbooleanfalse

Whether the overlay may extend beyond the map container, e.g. a tooltip of a marker near the edge of a small map. The overlay is then shown as popover in the top layer of the page, above all other content, while remaining in its map pane in the DOM (for styling and events).

contentDivOverlayContent''

Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be passed to the function. The function should return a String, HTMLElement or DocumentFragment to be used in the overlay. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
contentupdateMaplairEventFired when the content of the overlay is updated.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
openOn(map: MaplairMap, …args: any[])this

Adds the overlay to the map. Alternative to map.openPopup(popup)/.openTooltip(tooltip).

close()this

Closes the overlay. Alternative to map.closePopup(popup)/.closeTooltip(tooltip) and layer.closePopup()/.closeTooltip().

toggle(layer?: Layer, …args: any[])this

Opens or closes the overlay bound to layer depending on its current state. Argument may be omitted only for overlay bound to layer. Alternative to layer.togglePopup()/.toggleTooltip().

onAdd(map: MaplairMap)void

Adds the overlay to the map.

onRemove(map: MaplairMap)void

Removes the overlay from the map.

getLatLng()LatLng

Returns the geographical point of the overlay.

setLatLng(latlng: LatLngExpression)this

Sets the geographical point where the overlay will open.

getContent()DivOverlayContent

Returns the content of the overlay.

setContent(content: DivOverlayContent)this

Sets the HTML content of the overlay. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. A DocumentFragment can be passed as well. If a function is passed the source layer will be passed to the function. The function should return a String, HTMLElement or DocumentFragment to be used in the overlay.

getElement()HTMLElement

Returns the HTML container of the overlay.

update()void

Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.

getEvents()Record<string, EventListener>

Returns the map events the overlay listens to.

isOpen()boolean

Returns true when the overlay is visible on the map.

bringToFront()this

Brings this overlay in front of other overlays (in the same map pane).

bringToBack()this

Brings this overlay to the back of other overlays (in the same map pane).

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Tooltip extends DivOverlay

Used to display small texts on top of map layers.

Usage example

If you want to just bind a tooltip to marker:

marker.bindTooltip("my tooltip text").openTooltip();

Path overlays like polylines also have a bindTooltip method.

A tooltip can be also standalone:

const tooltip = new Tooltip()
	.setLatLng(latlng)
	.setContent('Hello world!<br />This is a nice tooltip.')
	.addTo(map);

or

const tooltip = new Tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'})
	.addTo(map);

Security note. Tooltip string content is rendered as HTML. If your content may include untrusted input (e.g. data from users or external APIs), sanitize it with a library like DOMPurify, or build a DOM element using textContent to render it as plain text:

const el = document.createElement('div');
el.textContent = untrustedString;
marker.bindTooltip(el);

Note about tooltip offset. Maplair takes two options in consideration for computing tooltip offsetting:

  • the offset Tooltip option: it defaults to [0, 0], and it's specific to one tooltip. Add a positive x offset to move the tooltip to the right, and a positive y offset to move it to the bottom. Negatives will move to the left and top.
  • the tooltipAnchor Icon option: this will only be considered for Marker. You should adapt this value if you use a custom icon.

Constructor

ConstructorDescription
new Tooltip(options?: TooltipOptions | undefined, source?: Layer | undefined)

Instantiates a Tooltip object given an optional options object that describes its appearance and location and an optional source object that is used to tag the tooltip with a reference to the Layer to which it refers.

new Tooltip(latlng: LatLngExpression, options?: TooltipOptions | undefined)

Instantiates a Tooltip object given latlng where the tooltip will open and an optional options object that describes its appearance and location.

Options

OptionTypeDefaultDescription
panestring'tooltipPane'

Map pane where the tooltip will be added.

offsetPointExpression[0, 0]

Optional offset of the tooltip position.

direction'right'|'left'|'top'|'bottom'|'center'|'auto''auto'

Direction where to open the tooltip. Possible values are: right, left, top, bottom, center, auto. auto chooses the direction with enough space when opening the tooltip: preferably the side towards the center of the map (right or left), otherwise the opposite side, top or bottom. The tooltip is shifted along that side to stay within the map (within the viewport if overflow is set), its tip still pointing at the source.

permanentbooleanfalse

Whether to open the tooltip permanently or only on pointerover.

stickybooleanfalse

If true, the tooltip will follow the pointer instead of being fixed at the feature center.

opacitynumber0.9

Tooltip container opacity.

Options inherited from DivOverlay
OptionTypeDefaultDescription
interactivebooleanfalse

If true, the popup/tooltip will listen to the pointer events.

offsetPointExpression[0, 0]

The offset of the overlay position.

classNamestring''

A custom CSS class name to assign to the overlay.

panestring

Map pane where the overlay will be added.

overflowbooleanfalse

Whether the overlay may extend beyond the map container, e.g. a tooltip of a marker near the edge of a small map. The overlay is then shown as popover in the top layer of the page, above all other content, while remaining in its map pane in the DOM (for styling and events).

contentDivOverlayContent''

Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be passed to the function. The function should return a String, HTMLElement or DocumentFragment to be used in the overlay. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from DivOverlay
EventDataDescription
contentupdateMaplairEventFired when the content of the overlay is updated.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
setOpacity(opacity: number)void

Sets the opacity of the tooltip.

Methods inherited from DivOverlay
MethodReturnsDescription
openOn(map: MaplairMap, …args: any[])this

Adds the overlay to the map. Alternative to map.openPopup(popup)/.openTooltip(tooltip).

close()this

Closes the overlay. Alternative to map.closePopup(popup)/.closeTooltip(tooltip) and layer.closePopup()/.closeTooltip().

toggle(layer?: Layer, …args: any[])this

Opens or closes the overlay bound to layer depending on its current state. Argument may be omitted only for overlay bound to layer. Alternative to layer.togglePopup()/.toggleTooltip().

onAdd(map: MaplairMap)void

Adds the overlay to the map.

onRemove(map: MaplairMap)void

Removes the overlay from the map.

getLatLng()LatLng

Returns the geographical point of the overlay.

setLatLng(latlng: LatLngExpression)this

Sets the geographical point where the overlay will open.

getContent()DivOverlayContent

Returns the content of the overlay.

setContent(content: DivOverlayContent)this

Sets the HTML content of the overlay. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. A DocumentFragment can be passed as well. If a function is passed the source layer will be passed to the function. The function should return a String, HTMLElement or DocumentFragment to be used in the overlay.

getElement()HTMLElement

Returns the HTML container of the overlay.

update()void

Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded.

getEvents()Record<string, EventListener>

Returns the map events the overlay listens to.

isOpen()boolean

Returns true when the overlay is visible on the map.

bringToFront()this

Brings this overlay in front of other overlays (in the same map pane).

bringToBack()this

Brings this overlay to the back of other overlays (in the same map pane).

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

TileLayer extends GridLayer

Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under Layer. Extends GridLayer.

URL template

A string of the following form:

'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png'

{s} means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; a, b or c by default, can be omitted), {z} — zoom level, {x} and {y} — tile coordinates. {r} can be used to add "@2x" to the URL to load retina tiles.

You can use custom keys in the template, which will be evaluated from TileLayer options, like this:

new TileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'});

Layers extending TileLayer might reimplement the getTileUrl() method.

Usage example

new TileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'}).addTo(map);

Constructor

ConstructorDescription
new TileLayer(url: string, options?: TileLayerOptions & Record<string, unknown>)

Instantiates a tile layer object given a URL template and optionally an options object.

url
The URL template.
options
The options, and the values of custom keys of the URL template.

Options

OptionTypeDefaultDescription
minZoomnumber0

The minimum zoom level down to which this layer will be displayed (inclusive).

maxZoomnumber18

The maximum zoom level up to which this layer will be displayed (inclusive).

subdomainsstring|string[]'abc'

Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.

errorTileUrlstring''

URL to the tile image to show in place of the tile that failed to load.

zoomOffsetnumber0

The zoom number used in tile URLs will be offset with this value.

tmsbooleanfalse

If true, inverses Y axis numbering for tiles (turn this on for TMS services).

zoomReversebooleanfalse

If set to true, the zoom number used in tile URLs will be reversed (maxZoom - zoom instead of zoom).

detectRetinabooleanfalse

If true and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the tiles. If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. Refer to CORS Settings for valid String values.

referrerPolicyReferrerPolicy'strict-origin-when-cross-origin'

Sets the tiles' referrerPolicy attribute set to the String provided. See HTMLImageElement.referrerPolicy for possible values.

Tile providers might require you to use a specific referrer policy (e.g. to verify API tokens or prevent abuse). Specifically, if you are using tiles from tile.openstreetmap.org or tile.osm.org, you should not change this value.

fetchOptionsRequestInit|nullnull

If set, the tiles are loaded with fetch() using these options (see RequestInit), e.g. {headers: {Authorization: 'Bearer …'}} for tile servers requiring custom HTTP headers. Requests of tiles that are no longer needed (e.g. after panning or zooming away) are aborted. Cross-origin tile servers have to allow such requests with CORS headers.

Options inherited from GridLayer
OptionTypeDefaultDescription
tileSizenumber|Point256

Width and height of tiles in the grid. Use a number if width and height are equal, or Point(width, height) otherwise.

opacitynumber1

Opacity of the tiles. Can be used in the createTile() function.

placeholderstring|nullnull

A CSS background shown in place of tiles while they are loading, e.g. '#ddd' or 'url(loading.svg) center no-repeat #eee'. Tiles with a placeholder appear without fading in.

updateWhenIdlebooleanfalse

Load new tiles only when panning ends.

updateWhenZoomingbooleantrue

By default, a smooth zoom animation (during a pinch zoom or a flyTo()) will update grid layers every integer zoom level. Setting this option to false will update the grid layer only when the smooth animation ends.

updateIntervalnumber200

Tiles will not update more than once every updateInterval milliseconds when panning.

zIndexnumber1

The explicit zIndex of the tile layer.

boundsLatLngBoundsExpression|nullnull

If set, tiles will only be loaded inside the set LatLngBounds.

minZoomnumber0

The minimum zoom level down to which this layer will be displayed (inclusive).

maxZoomnumber

The maximum zoom level up to which this layer will be displayed (inclusive).

maxNativeZoomnumber

Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than maxNativeZoom will be loaded from maxNativeZoom level and auto-scaled.

minNativeZoomnumber

Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than minNativeZoom will be loaded from minNativeZoom level and auto-scaled.

noWrapbooleanfalse

Whether the layer is wrapped around the antimeridian. If true, the GridLayer will only be displayed once at low zoom levels. Has no effect when the map CRS doesn't wrap around. Can be used in combination with bounds to prevent requesting tiles outside the CRS limits.

panestring'tilePane'

Map pane where the grid layer will be added.

classNamestring''

A custom class name to assign to the tile layer. Empty by default.

pixelatedbooleanfalse

Whether to scale the tiles with nearest-neighbour interpolation (image-rendering: pixelated) instead of smoothing them, so that their pixels stay crisp, e.g. while zooming or beyond maxNativeZoom. Useful for raster data, pixel art or scientific imagery.

keepBuffernumber2

When panning the map, keep this many rows and columns of tiles before unloading them.

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
tileabortTileEventFired when a tile was loading but is now not wanted.
Events inherited from GridLayer
EventDataDescription
loadingMaplairEventFired when the grid layer starts loading tiles.
tileunloadTileEventFired when a tile is removed (e.g. when a tile goes off the screen).
tileloadstartTileEventFired when a tile is requested and starts loading.
tileerrorTileErrorEventFired when there is an error loading a tile.
tileloadTileEventFired when a tile loads.
loadMaplairEventFired when the grid layer loaded all visible tiles.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Extension methods

MethodReturnsDescription
getTileUrl(coords: Point)string

Called only internally, returns the URL for a tile given its coordinates. Classes extending TileLayer can override this function to provide custom tile URL naming schemes.

Other methods

MethodReturnsDescription
setUrl(url: string, noRedraw?: boolean)this

Updates the layer's URL template and redraws it (unless noRedraw is set to true). If the URL does not change, the layer will not be redrawn unless the noRedraw parameter is set to false. The current tiles stay visible until the new tiles have loaded, to avoid flickering.

createTile(coords: Point, done?: TileDoneCallback)HTMLImageElement

Called only internally, overrides GridLayer's createTile() to return an <img> HTML element with the appropriate image URL given coords. The done callback is called when the tile has been loaded.

Methods inherited from GridLayer
MethodReturnsDescription
onAdd(map: MaplairMap)void

Creates the container of the tiles and loads the tiles.

beforeAdd(map: MaplairMap)void

Registers the zoom limits of the layer on the map.

onRemove(map: MaplairMap)void

Removes the tiles from the map.

bringToFront()this

Brings the tile layer to the top of all tile layers.

bringToBack()this

Brings the tile layer to the bottom of all tile layers.

getContainer()HTMLElement

Returns the HTML element that contains the tiles for this layer.

setOpacity(opacity: number)this

Changes the opacity of the grid layer.

setZIndex(zIndex: number)this

Changes the zIndex of the grid layer.

isLoading()boolean

Returns true if any tile in the grid layer has not finished loading.

redraw()this

Causes the layer to clear all the tiles and request them again.

getEvents()Record<string, Function>

Returns the map events the layer listens to, see Layer.

getTileSize()Point

Normalizes the tileSize option into a point. Used by the createTile() method.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

WMSTileLayer extends TileLayer

Used to display WMS services as tile layers on the map. Extends TileLayer.

Usage example

const nexrad = new WMSTileLayer("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", {
	layers: 'nexrad-n0r-900913',
	format: 'image/png',
	transparent: true,
	attribution: "Weather data © 2012 IEM Nexrad"
});

Constructor

ConstructorDescription
new WMSTileLayer(url: string, options: WMSTileLayerOptions & Record<string, unknown>)

Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object.

url
The base URL of the WMS service.
options
The options and WMS parameters.

Options

OptionTypeDefaultDescription
layersstring''

(required) Comma-separated list of WMS layers to show.

stylesstring''

Comma-separated list of WMS styles.

formatstring'image/jpeg'

WMS image format (use 'image/png' for layers with transparency).

transparentbooleanfalse

If true, the WMS service will return images with transparency.

versionstring'1.1.1'

Version of the WMS service to use.

crsCRS|nullnull

Coordinate Reference System to use for the WMS requests, defaults to map CRS. Don't change this if you're not sure what it means.

uppercasebooleanfalse

If true, WMS request parameter keys will be uppercase.

Options inherited from TileLayer
OptionTypeDefaultDescription
minZoomnumber0

The minimum zoom level down to which this layer will be displayed (inclusive).

maxZoomnumber18

The maximum zoom level up to which this layer will be displayed (inclusive).

subdomainsstring|string[]'abc'

Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings.

errorTileUrlstring''

URL to the tile image to show in place of the tile that failed to load.

zoomOffsetnumber0

The zoom number used in tile URLs will be offset with this value.

tmsbooleanfalse

If true, inverses Y axis numbering for tiles (turn this on for TMS services).

zoomReversebooleanfalse

If set to true, the zoom number used in tile URLs will be reversed (maxZoom - zoom instead of zoom).

detectRetinabooleanfalse

If true and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the tiles. If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. Refer to CORS Settings for valid String values.

referrerPolicyReferrerPolicy'strict-origin-when-cross-origin'

Sets the tiles' referrerPolicy attribute set to the String provided. See HTMLImageElement.referrerPolicy for possible values.

Tile providers might require you to use a specific referrer policy (e.g. to verify API tokens or prevent abuse). Specifically, if you are using tiles from tile.openstreetmap.org or tile.osm.org, you should not change this value.

fetchOptionsRequestInit|nullnull

If set, the tiles are loaded with fetch() using these options (see RequestInit), e.g. {headers: {Authorization: 'Bearer …'}} for tile servers requiring custom HTTP headers. Requests of tiles that are no longer needed (e.g. after panning or zooming away) are aborted. Cross-origin tile servers have to allow such requests with CORS headers.

Options inherited from GridLayer
OptionTypeDefaultDescription
tileSizenumber|Point256

Width and height of tiles in the grid. Use a number if width and height are equal, or Point(width, height) otherwise.

opacitynumber1

Opacity of the tiles. Can be used in the createTile() function.

placeholderstring|nullnull

A CSS background shown in place of tiles while they are loading, e.g. '#ddd' or 'url(loading.svg) center no-repeat #eee'. Tiles with a placeholder appear without fading in.

updateWhenIdlebooleanfalse

Load new tiles only when panning ends.

updateWhenZoomingbooleantrue

By default, a smooth zoom animation (during a pinch zoom or a flyTo()) will update grid layers every integer zoom level. Setting this option to false will update the grid layer only when the smooth animation ends.

updateIntervalnumber200

Tiles will not update more than once every updateInterval milliseconds when panning.

zIndexnumber1

The explicit zIndex of the tile layer.

boundsLatLngBoundsExpression|nullnull

If set, tiles will only be loaded inside the set LatLngBounds.

minZoomnumber0

The minimum zoom level down to which this layer will be displayed (inclusive).

maxZoomnumber

The maximum zoom level up to which this layer will be displayed (inclusive).

maxNativeZoomnumber

Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than maxNativeZoom will be loaded from maxNativeZoom level and auto-scaled.

minNativeZoomnumber

Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than minNativeZoom will be loaded from minNativeZoom level and auto-scaled.

noWrapbooleanfalse

Whether the layer is wrapped around the antimeridian. If true, the GridLayer will only be displayed once at low zoom levels. Has no effect when the map CRS doesn't wrap around. Can be used in combination with bounds to prevent requesting tiles outside the CRS limits.

panestring'tilePane'

Map pane where the grid layer will be added.

classNamestring''

A custom class name to assign to the tile layer. Empty by default.

pixelatedbooleanfalse

Whether to scale the tiles with nearest-neighbour interpolation (image-rendering: pixelated) instead of smoothing them, so that their pixels stay crisp, e.g. while zooming or beyond maxNativeZoom. Useful for raster data, pixel art or scientific imagery.

keepBuffernumber2

When panning the map, keep this many rows and columns of tiles before unloading them.

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from TileLayer
EventDataDescription
tileabortTileEventFired when a tile was loading but is now not wanted.
Events inherited from GridLayer
EventDataDescription
loadingMaplairEventFired when the grid layer starts loading tiles.
tileunloadTileEventFired when a tile is removed (e.g. when a tile goes off the screen).
tileloadstartTileEventFired when a tile is requested and starts loading.
tileerrorTileErrorEventFired when there is an error loading a tile.
tileloadTileEventFired when a tile loads.
loadMaplairEventFired when the grid layer loaded all visible tiles.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
getLegendUrl(params?: Record<string, any>)string

Returns the URL of the legend image (a GetLegendGraphic request) of the first of the layers (with its style, if any), with the version, format and uppercase option of the layer. params change or add parameters, e.g. {layer: 'roads', width: 20, height: 20} or vendor parameters like legend_options.

setParams(params: Record<string, any>, noRedraw?: boolean)this

Merges an object with the new parameters and re-requests tiles on the current screen (unless noRedraw was set to true). The current tiles stay visible until the new tiles have loaded, to avoid flickering.

Methods inherited from TileLayer
MethodReturnsDescription
setUrl(url: string, noRedraw?: boolean)this

Updates the layer's URL template and redraws it (unless noRedraw is set to true). If the URL does not change, the layer will not be redrawn unless the noRedraw parameter is set to false. The current tiles stay visible until the new tiles have loaded, to avoid flickering.

createTile(coords: Point, done?: TileDoneCallback)HTMLImageElement

Called only internally, overrides GridLayer's createTile() to return an <img> HTML element with the appropriate image URL given coords. The done callback is called when the tile has been loaded.

getTileUrl(coords: Point)string

Called only internally, returns the URL for a tile given its coordinates. Classes extending TileLayer can override this function to provide custom tile URL naming schemes.

Methods inherited from GridLayer
MethodReturnsDescription
onAdd(map: MaplairMap)void

Creates the container of the tiles and loads the tiles.

beforeAdd(map: MaplairMap)void

Registers the zoom limits of the layer on the map.

onRemove(map: MaplairMap)void

Removes the tiles from the map.

bringToFront()this

Brings the tile layer to the top of all tile layers.

bringToBack()this

Brings the tile layer to the bottom of all tile layers.

getContainer()HTMLElement

Returns the HTML element that contains the tiles for this layer.

setOpacity(opacity: number)this

Changes the opacity of the grid layer.

setZIndex(zIndex: number)this

Changes the zIndex of the grid layer.

isLoading()boolean

Returns true if any tile in the grid layer has not finished loading.

redraw()this

Causes the layer to clear all the tiles and request them again.

getEvents()Record<string, Function>

Returns the map events the layer listens to, see Layer.

getTileSize()Point

Normalizes the tileSize option into a point. Used by the createTile() method.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Properties

PropertyTypeDescription
wmsParamsRecord<string, any>

The parameters of the WMS requests, see setParams().

Static members

PropertyTypeDescription
defaultWmsParamsRecord<string, any>

The default WMS parameters, which the options override, see WMSTileLayerOptions.

ImageOverlay extends Layer

Used to load and display a single image over specific bounds of the map. Extends Layer.

Usage example

const imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
	imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
new ImageOverlay(imageUrl, imageBounds).addTo(map);

Constructor

ConstructorDescription
new ImageOverlay(url: string | HTMLImageElement, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions)

Instantiates an image overlay object given the URL of the image (or an image element) and the geographical bounds it is tied to.

Options

OptionTypeDefaultDescription
opacitynumber1

The opacity of the image overlay.

altstring''

Text for the alt attribute of the image (useful for accessibility).

interactivebooleanfalse

If true, the image overlay will emit pointer events when clicked or hovered.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the image. If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values.

errorOverlayUrlstring''

URL to the overlay image to show in place of the overlay that failed to load.

zIndexnumber1

The explicit zIndex of the overlay layer.

classNamestring''

A custom class name to assign to the image. Empty by default.

pixelatedbooleanfalse

Whether to scale the image with nearest-neighbour interpolation (image-rendering: pixelated) instead of smoothing it, so that its pixels stay crisp when zoomed in. Useful for raster data, pixel art or scientific imagery.

decodingstring'auto'

Tells the browser whether to decode the image in a synchronous fashion, as per the decoding HTML attribute. If the image overlay is flickering when being added/removed, set this option to 'sync'.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
loadMaplairEventFired when the ImageOverlay layer has loaded its image.
errorMaplairEventFired when the ImageOverlay layer fails to load its image.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
onAdd(map: MaplairMap)void
onRemove(map: MaplairMap)void
setOpacity(opacity: number)this

Sets the opacity of the overlay.

setStyle(styleOpts: { opacity?: number; })this

Sets the opacity of the overlay from the given style options, e.g. by FeatureGroup.setStyle().

bringToFront()this

Brings the layer to the top of all overlays.

bringToBack()this

Brings the layer to the bottom of all overlays.

setUrl(url: string)this

Changes the URL of the image.

setBounds(bounds: LatLngBoundsExpression)this

Update the bounds that this ImageOverlay covers.

getEvents()Record<string, EventListener>

Returns the map events the overlay listens to.

setZIndex(value: number)this

Changes the zIndex of the image overlay.

getBounds()LatLngBounds

Get the bounds that this ImageOverlay covers.

getElement()HTMLElement | SVGElement

Returns the instance of HTMLImageElement used by this overlay (HTMLVideoElement for VideoOverlay, SVGElement for SVGOverlay).

getCenter()LatLng

Returns the center of the ImageOverlay.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

VideoOverlay extends ImageOverlay

Used to load and display a video player over specific bounds of the map. Extends ImageOverlay.

A video overlay uses the <video> HTML element; getElement() returns the instance of HTMLVideoElement used by this overlay.

Usage example

const videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
	videoBounds = [[ 32, -130], [ 13, -100]];
new VideoOverlay(videoUrl, videoBounds ).addTo(map);

Constructor

ConstructorDescription
new VideoOverlay(video: string | string[] | HTMLVideoElement, bounds: LatLngBoundsExpression, options?: VideoOverlayOptions | undefined)

Instantiates a video overlay object given the URL of the video (or array of URLs, or even a video element) and the geographical bounds it is tied to.

Options

OptionTypeDefaultDescription
autoplaybooleantrue

Whether the video starts playing automatically when loaded. On some browsers autoplay will only work with muted: true.

controlsbooleanfalse

Whether the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback.

loopbooleantrue

Whether the video will loop back to the beginning when played.

keepAspectRatiobooleantrue

Whether the video will save aspect ratio after the projection.

mutedbooleanfalse

Whether the video starts on mute when loaded.

playsInlinebooleantrue

Mobile browsers will play the video right where it is instead of open it up in fullscreen mode.

Options inherited from ImageOverlay
OptionTypeDefaultDescription
opacitynumber1

The opacity of the image overlay.

altstring''

Text for the alt attribute of the image (useful for accessibility).

interactivebooleanfalse

If true, the image overlay will emit pointer events when clicked or hovered.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the image. If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values.

errorOverlayUrlstring''

URL to the overlay image to show in place of the overlay that failed to load.

zIndexnumber1

The explicit zIndex of the overlay layer.

classNamestring''

A custom class name to assign to the image. Empty by default.

pixelatedbooleanfalse

Whether to scale the image with nearest-neighbour interpolation (image-rendering: pixelated) instead of smoothing it, so that its pixels stay crisp when zoomed in. Useful for raster data, pixel art or scientific imagery.

decodingstring'auto'

Tells the browser whether to decode the image in a synchronous fashion, as per the decoding HTML attribute. If the image overlay is flickering when being added/removed, set this option to 'sync'.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
loadMaplairEventFired when the video has finished loading the first frame.
Events inherited from ImageOverlay
EventDataDescription
loadMaplairEventFired when the ImageOverlay layer has loaded its image.
errorMaplairEventFired when the ImageOverlay layer fails to load its image.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Methods inherited from ImageOverlay
MethodReturnsDescription
onAdd(map: MaplairMap)void
onRemove(map: MaplairMap)void
setOpacity(opacity: number)this

Sets the opacity of the overlay.

setStyle(styleOpts: { opacity?: number; })this

Sets the opacity of the overlay from the given style options, e.g. by FeatureGroup.setStyle().

bringToFront()this

Brings the layer to the top of all overlays.

bringToBack()this

Brings the layer to the bottom of all overlays.

setUrl(url: string)this

Changes the URL of the image.

setBounds(bounds: LatLngBoundsExpression)this

Update the bounds that this ImageOverlay covers.

getEvents()Record<string, EventListener>

Returns the map events the overlay listens to.

setZIndex(value: number)this

Changes the zIndex of the image overlay.

getBounds()LatLngBounds

Get the bounds that this ImageOverlay covers.

getElement()HTMLElement | SVGElement

Returns the instance of HTMLImageElement used by this overlay (HTMLVideoElement for VideoOverlay, SVGElement for SVGOverlay).

getCenter()LatLng

Returns the center of the ImageOverlay.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

SVGOverlay extends ImageOverlay

Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends ImageOverlay.

An SVG overlay uses the <svg> element; getElement() returns the instance of SVGElement used by this overlay.

Usage example

const svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
svgElement.setAttribute('viewBox', "0 0 200 200");
svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
const svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
new SVGOverlay(svgElement, svgElementBounds).addTo(map);

Constructor

ConstructorDescription
new SVGOverlay(svg: SVGElement, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions | undefined)

Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to. A viewBox attribute is required on the SVG element to zoom in and out properly.

Events

Events inherited from ImageOverlay
EventDataDescription
loadMaplairEventFired when the ImageOverlay layer has loaded its image.
errorMaplairEventFired when the ImageOverlay layer fails to load its image.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Methods inherited from ImageOverlay
MethodReturnsDescription
onAdd(map: MaplairMap)void
onRemove(map: MaplairMap)void
setOpacity(opacity: number)this

Sets the opacity of the overlay.

setStyle(styleOpts: { opacity?: number; })this

Sets the opacity of the overlay from the given style options, e.g. by FeatureGroup.setStyle().

bringToFront()this

Brings the layer to the top of all overlays.

bringToBack()this

Brings the layer to the bottom of all overlays.

setUrl(url: string)this

Changes the URL of the image.

setBounds(bounds: LatLngBoundsExpression)this

Update the bounds that this ImageOverlay covers.

getEvents()Record<string, EventListener>

Returns the map events the overlay listens to.

setZIndex(value: number)this

Changes the zIndex of the image overlay.

getBounds()LatLngBounds

Get the bounds that this ImageOverlay covers.

getElement()HTMLElement | SVGElement

Returns the instance of HTMLImageElement used by this overlay (HTMLVideoElement for VideoOverlay, SVGElement for SVGOverlay).

getCenter()LatLng

Returns the center of the ImageOverlay.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

HeatLayer extends BlanketOverlay

A heatmap of points, each with an optional intensity, drawn on a canvas: the points are drawn as blurred circles adding up, and colored by a gradient. Nearby points are merged into a grid for speed, so that tens of thousands of points stay fast.

Inspired by the Leaflet.heat plugin and its simpleheat algorithm.

Usage example

new HeatLayer([
	[47.27, 11.40, 0.5], // latitude, longitude, intensity
	[47.28, 11.41],
	new LatLng(47.26, 11.39)
], {radius: 20}).addTo(map);

Constructor

ConstructorDescription
new HeatLayer(latlngs?: LatLngExpression[], options?: HeatLayerOptions)

Creates a heatmap of the given points: LatLngs or arrays [lat, lng, intensity] (the intensity defaults to 1).

Options

OptionTypeDefaultDescription
radiusnumber25

The radius of each point in pixels.

blurnumber15

The amount of blur in pixels.

maxnumber1

The intensity with the strongest color.

maxZoomnumber

The zoom level where the points reach the full intensity; below it, the intensity is halved per zoom level. By default the maximum zoom of the map.

minOpacitynumber0.05

The minimum opacity of the heat.

gradientRecord<number, string>{0.4: 'blue', 0.6: 'cyan', 0.7: 'lime', 0.8: 'yellow', 1: 'red'}

The colors for the intensities from 0 to 1, any CSS colors.

panestring'overlayPane'

The map pane of the layer.

Options inherited from BlanketOverlay
OptionTypeDefaultDescription
paddingnumber0.1

How 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.

continuousbooleanfalse

When false, the blanket will update its position only when the map state settles (after a pan/zoom animation). When true, it will update when the map state changes (during pan/zoom animations).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
setLatLngs(latlngs: LatLngExpression[])this

Replaces the points of the heatmap.

addLatLng(latlng: LatLngExpression)this

Adds a point to the heatmap.

getLatLngs()LatLngExpression[]

Returns the points of the heatmap.

setOptions(options: HeatLayerOptions)this

Changes the options, e.g. the radius or the gradient.

redraw()this

Redraws the heatmap.

Methods inherited from BlanketOverlay
MethodReturnsDescription
onAdd(map: MaplairMap)void
onRemove(map: MaplairMap)void
getEvents()Record<string, EventListener>

Returns the map events the blanket listens to.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Path extends Layer

An abstract class that contains options and methods shared between vector overlays (Polyline, Polygon, Rectangle, Circle, CircleMarker). Do not use it directly. Extends Layer.

Options

OptionTypeDefaultDescription
strokebooleantrue

Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.

colorstring'#3388ff'

Stroke color.

weightnumber3

Stroke width in pixels.

opacitynumber1

Stroke opacity.

lineCapstring'round'

A string that defines shape to be used at the end of the stroke.

lineJoinstring'round'

A string that defines shape to be used at the corners of the stroke.

dashArraystring|nullnull

A string that defines the stroke dash pattern.

dashOffsetstring|nullnull

A string that defines the distance into the dash pattern to start the dash.

fillbooleanfalse

Whether to fill the path with color. Set it to false to disable filling on polygons or circles. The default depends on the class: true for polygons and circles.

fillColorstring|nullnull

Fill color. Defaults to the value of the color option.

fillOpacitynumber0.2

Fill opacity.

fillRulestring'evenodd'

A string that defines how the inside of a shape is determined.

classNamestring

Custom class name set on an element. Only for SVG renderer. Applied when the element is created; setStyle does not update it afterwards.

rendererRenderer

Use this specific instance of Renderer for this path. If not set, the path uses the map's renderer (SVG by default), or in a custom pane, a renderer of the same kind created for that pane. If set, it overrides the pane option.

dashSpeednumber0

Animates the dashes of the dashArray along the path ("marching ants"), e.g. to show the direction of a flow: the speed in pixels per second, negative for the opposite direction. Not animated with reduced motion.

Added by the optional module maplair/dash-animation.

arrowheadsboolean|{size?: number, repeat?: number, color?: string}false

Arrowheads along a polyline: true for one at the end of each line, or an object with the size (in pixels, default 10), repeat (an arrowhead every that many pixels instead) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

textstring|{content: string, repeat?: boolean, center?: boolean, offset?: number, fontSize?: number, color?: string}|nullnull

Text along a polyline, e.g. a street name: the text, or an object with the content, repeat (repeat the text along the whole line), center (center it on the line), offset (in pixels, perpendicular to the line), fontSize (in pixels, default 12) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
beforeAdd(map: MaplairMap)void

Gets the renderer of the path from the map, before it is added.

onAdd()void

Adds the path to its renderer.

onRemove()void

Removes the path from its renderer.

redraw()this

Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.

setStyle(style: PathOptions)this

Changes the appearance of a Path based on the options in the PathOptions object. Note that className is an exception: it is applied only when the path element is created, so passing it here updates the option but leaves the element's class unchanged.

bringToFront()this

Brings the layer to the top of all path layers.

bringToBack()this

Brings the layer to the bottom of all path layers.

getElement()SVGPathElement | undefined

Returns the SVG path element of the layer, if it is rendered by the SVG renderer.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Polyline extends Path

A class for drawing polyline overlays on a map. Extends Path.

Usage example

// create a red polyline from an array of LatLng points
const latlngs = [
	[45.51, -122.68],
	[37.77, -122.43],
	[34.04, -118.2]
];

const polyline = new Polyline(latlngs, {color: 'red'}).addTo(map);

// zoom the map to the polyline
map.fitBounds(polyline.getBounds());

You can also pass a multi-dimensional array to represent a MultiPolyline shape:

// create a red polyline from an array of arrays of LatLng points
const latlngs = [
	[[45.51, -122.68],
	 [37.77, -122.43],
	 [34.04, -118.2]],
	[[40.78, -73.91],
	 [41.83, -87.62],
	 [32.76, -96.72]]
];

Constructor

ConstructorDescription
new Polyline(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][], options?: PolylineOptions)

Instantiates a polyline object given an array of geographical points and optionally an options object. You can create a Polyline object with multiple separate lines (MultiPolyline) by passing an array of arrays of geographic points.

Options

OptionTypeDefaultDescription
smoothFactornumber0.5

How much to simplify the polyline on each zoom level (Douglas–Peucker epsilon, in pixels). Higher values mean faster rendering but less accuracy; lower values mean more accuracy but slower rendering.

noClipbooleanfalse

Disable polyline clipping.

Options inherited from Path
OptionTypeDefaultDescription
strokebooleantrue

Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.

colorstring'#3388ff'

Stroke color.

weightnumber3

Stroke width in pixels.

opacitynumber1

Stroke opacity.

lineCapstring'round'

A string that defines shape to be used at the end of the stroke.

lineJoinstring'round'

A string that defines shape to be used at the corners of the stroke.

dashArraystring|nullnull

A string that defines the stroke dash pattern.

dashOffsetstring|nullnull

A string that defines the distance into the dash pattern to start the dash.

fillbooleanfalse

Whether to fill the path with color. Set it to false to disable filling on polygons or circles. The default depends on the class: true for polygons and circles.

fillColorstring|nullnull

Fill color. Defaults to the value of the color option.

fillOpacitynumber0.2

Fill opacity.

fillRulestring'evenodd'

A string that defines how the inside of a shape is determined.

classNamestring

Custom class name set on an element. Only for SVG renderer. Applied when the element is created; setStyle does not update it afterwards.

rendererRenderer

Use this specific instance of Renderer for this path. If not set, the path uses the map's renderer (SVG by default), or in a custom pane, a renderer of the same kind created for that pane. If set, it overrides the pane option.

dashSpeednumber0

Animates the dashes of the dashArray along the path ("marching ants"), e.g. to show the direction of a flow: the speed in pixels per second, negative for the opposite direction. Not animated with reduced motion.

Added by the optional module maplair/dash-animation.

arrowheadsboolean|{size?: number, repeat?: number, color?: string}false

Arrowheads along a polyline: true for one at the end of each line, or an object with the size (in pixels, default 10), repeat (an arrowhead every that many pixels instead) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

textstring|{content: string, repeat?: boolean, center?: boolean, offset?: number, fontSize?: number, color?: string}|nullnull

Text along a polyline, e.g. a street name: the text, or an object with the content, repeat (repeat the text along the whole line), center (center it on the line), offset (in pixels, perpendicular to the line), fontSize (in pixels, default 12) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
getLatLngs()LatLng[] | LatLng[][] | LatLng[][][]

Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.

setLatLngs(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][])this

Replaces all the points in the polyline with the given array of geographical points.

isEmpty()boolean

Returns true if the Polyline has no LatLngs.

closestLayerPoint(p: PointExpression)(Point & { distance: number; }) | null

Returns the point closest to p on the Polyline, with its distance to p in pixels, or null if the polyline is not visible.

getCenter()LatLng

Returns the center (centroid) of the polyline.

getBounds()LatLngBounds

Returns the LatLngBounds of the path.

addLatLng(latlng: LatLngExpression, latlngs?: LatLng[])this

Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with getLatLngs).

toGeoJSON(precision?: number | false)Feature

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the polyline (as a GeoJSON LineString or MultiLineString Feature).

Methods inherited from Path
MethodReturnsDescription
beforeAdd(map: MaplairMap)void

Gets the renderer of the path from the map, before it is added.

onAdd()void

Adds the path to its renderer.

onRemove()void

Removes the path from its renderer.

redraw()this

Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.

setStyle(style: PathOptions)this

Changes the appearance of a Path based on the options in the PathOptions object. Note that className is an exception: it is applied only when the path element is created, so passing it here updates the option but leaves the element's class unchanged.

bringToFront()this

Brings the layer to the top of all path layers.

bringToBack()this

Brings the layer to the bottom of all path layers.

getElement()SVGPathElement | undefined

Returns the SVG path element of the layer, if it is rendered by the SVG renderer.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Polygon extends Polyline

A class for drawing polygon overlays on a map. Extends Polyline.

Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points.

Usage example

// create a red polygon from an array of LatLng points
const latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]];

const polygon = new Polygon(latlngs, {color: 'red'}).addTo(map);

// zoom the map to the polygon
map.fitBounds(polygon.getBounds());

You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape:

const latlngs = [
  [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
  [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
];

Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape.

const latlngs = [
  [ // first polygon
    [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring
    [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole
  ],
  [ // second polygon
    [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]]
  ]
];

Constructor

ConstructorDescription
new Polygon(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][], options?: PolygonOptions | undefined)

Instantiates a polygon object given an array of geographical points (or arrays of them for holes and multi-polygons) and optionally an options object.

Options

OptionTypeDefaultDescription
fillbooleantrue

Whether to fill the polygon with color.

Options inherited from Polyline
OptionTypeDefaultDescription
smoothFactornumber0.5

How much to simplify the polyline on each zoom level (Douglas–Peucker epsilon, in pixels). Higher values mean faster rendering but less accuracy; lower values mean more accuracy but slower rendering.

noClipbooleanfalse

Disable polyline clipping.

Options inherited from Path
OptionTypeDefaultDescription
strokebooleantrue

Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.

colorstring'#3388ff'

Stroke color.

weightnumber3

Stroke width in pixels.

opacitynumber1

Stroke opacity.

lineCapstring'round'

A string that defines shape to be used at the end of the stroke.

lineJoinstring'round'

A string that defines shape to be used at the corners of the stroke.

dashArraystring|nullnull

A string that defines the stroke dash pattern.

dashOffsetstring|nullnull

A string that defines the distance into the dash pattern to start the dash.

fillbooleanfalse

Whether to fill the path with color. Set it to false to disable filling on polygons or circles. The default depends on the class: true for polygons and circles.

fillColorstring|nullnull

Fill color. Defaults to the value of the color option.

fillOpacitynumber0.2

Fill opacity.

fillRulestring'evenodd'

A string that defines how the inside of a shape is determined.

classNamestring

Custom class name set on an element. Only for SVG renderer. Applied when the element is created; setStyle does not update it afterwards.

rendererRenderer

Use this specific instance of Renderer for this path. If not set, the path uses the map's renderer (SVG by default), or in a custom pane, a renderer of the same kind created for that pane. If set, it overrides the pane option.

dashSpeednumber0

Animates the dashes of the dashArray along the path ("marching ants"), e.g. to show the direction of a flow: the speed in pixels per second, negative for the opposite direction. Not animated with reduced motion.

Added by the optional module maplair/dash-animation.

arrowheadsboolean|{size?: number, repeat?: number, color?: string}false

Arrowheads along a polyline: true for one at the end of each line, or an object with the size (in pixels, default 10), repeat (an arrowhead every that many pixels instead) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

textstring|{content: string, repeat?: boolean, center?: boolean, offset?: number, fontSize?: number, color?: string}|nullnull

Text along a polyline, e.g. a street name: the text, or an object with the content, repeat (repeat the text along the whole line), center (center it on the line), offset (in pixels, perpendicular to the line), fontSize (in pixels, default 12) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Methods inherited from Polyline
MethodReturnsDescription
getLatLngs()LatLng[] | LatLng[][] | LatLng[][][]

Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.

setLatLngs(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][])this

Replaces all the points in the polyline with the given array of geographical points.

isEmpty()boolean

Returns true if the Polyline has no LatLngs.

closestLayerPoint(p: PointExpression)(Point & { distance: number; }) | null

Returns the point closest to p on the Polyline, with its distance to p in pixels, or null if the polyline is not visible.

getCenter()LatLng

Returns the center (centroid) of the polyline.

getBounds()LatLngBounds

Returns the LatLngBounds of the path.

addLatLng(latlng: LatLngExpression, latlngs?: LatLng[])this

Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with getLatLngs).

toGeoJSON(precision?: number | false)Feature

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the polyline (as a GeoJSON LineString or MultiLineString Feature).

Methods inherited from Path
MethodReturnsDescription
beforeAdd(map: MaplairMap)void

Gets the renderer of the path from the map, before it is added.

onAdd()void

Adds the path to its renderer.

onRemove()void

Removes the path from its renderer.

redraw()this

Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.

setStyle(style: PathOptions)this

Changes the appearance of a Path based on the options in the PathOptions object. Note that className is an exception: it is applied only when the path element is created, so passing it here updates the option but leaves the element's class unchanged.

bringToFront()this

Brings the layer to the top of all path layers.

bringToBack()this

Brings the layer to the bottom of all path layers.

getElement()SVGPathElement | undefined

Returns the SVG path element of the layer, if it is rendered by the SVG renderer.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Rectangle extends Polygon

A class for drawing rectangle overlays on a map. Extends Polygon.

Usage example

// define rectangle geographical bounds
const bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]];

// create an orange rectangle
new Rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map);

// zoom the map to the rectangle bounds
map.fitBounds(bounds);

Constructor

ConstructorDescription
new Rectangle(latLngBounds: LatLngBoundsExpression, options?: PolygonOptions)

Instantiates a rectangle object given the geographical bounds, and an optional options object.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
setBounds(latLngBounds: LatLngBoundsExpression)this

Redraws the rectangle with the passed bounds.

Methods inherited from Polyline
MethodReturnsDescription
getLatLngs()LatLng[] | LatLng[][] | LatLng[][][]

Returns an array of the points in the path, or nested arrays of points in case of multi-polyline.

setLatLngs(latlngs: LatLngExpression[] | LatLngExpression[][] | LatLngExpression[][][])this

Replaces all the points in the polyline with the given array of geographical points.

isEmpty()boolean

Returns true if the Polyline has no LatLngs.

closestLayerPoint(p: PointExpression)(Point & { distance: number; }) | null

Returns the point closest to p on the Polyline, with its distance to p in pixels, or null if the polyline is not visible.

getCenter()LatLng

Returns the center (centroid) of the polyline.

getBounds()LatLngBounds

Returns the LatLngBounds of the path.

addLatLng(latlng: LatLngExpression, latlngs?: LatLng[])this

Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with getLatLngs).

toGeoJSON(precision?: number | false)Feature

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the polyline (as a GeoJSON LineString or MultiLineString Feature).

Methods inherited from Path
MethodReturnsDescription
beforeAdd(map: MaplairMap)void

Gets the renderer of the path from the map, before it is added.

onAdd()void

Adds the path to its renderer.

onRemove()void

Removes the path from its renderer.

redraw()this

Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.

setStyle(style: PathOptions)this

Changes the appearance of a Path based on the options in the PathOptions object. Note that className is an exception: it is applied only when the path element is created, so passing it here updates the option but leaves the element's class unchanged.

bringToFront()this

Brings the layer to the top of all path layers.

bringToBack()this

Brings the layer to the bottom of all path layers.

getElement()SVGPathElement | undefined

Returns the SVG path element of the layer, if it is rendered by the SVG renderer.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Circle extends CircleMarker

A class for drawing circle overlays on a map with radius specified in meters. Extends CircleMarker, its setRadius() and getRadius() use meters.

It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion).

Usage example

new Circle([50.5, 30.5], {radius: 200}).addTo(map);

Constructor

ConstructorDescription
new Circle(latlng: LatLngExpression, options?: CircleOptions)

Instantiates a circle object given a geographical point, and an options object which contains the circle radius.

Options

OptionTypeDefaultDescription
radiusnumber

Radius of the circle, in meters.

Options inherited from CircleMarker
OptionTypeDefaultDescription
fillbooleantrue

Whether to fill the circle with color.

radiusnumber10

Radius of the circle marker, in CSS pixels.

displaceboolean

Whether to include this marker in the displacement of the map, see DisplaceHandler.

displaceIdstring

Stable identifier shared across marker instances that represent the same thing on different layers, so that DisplaceHandler puts them at the same displaced position.

Options inherited from Path
OptionTypeDefaultDescription
strokebooleantrue

Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.

colorstring'#3388ff'

Stroke color.

weightnumber3

Stroke width in pixels.

opacitynumber1

Stroke opacity.

lineCapstring'round'

A string that defines shape to be used at the end of the stroke.

lineJoinstring'round'

A string that defines shape to be used at the corners of the stroke.

dashArraystring|nullnull

A string that defines the stroke dash pattern.

dashOffsetstring|nullnull

A string that defines the distance into the dash pattern to start the dash.

fillbooleanfalse

Whether to fill the path with color. Set it to false to disable filling on polygons or circles. The default depends on the class: true for polygons and circles.

fillColorstring|nullnull

Fill color. Defaults to the value of the color option.

fillOpacitynumber0.2

Fill opacity.

fillRulestring'evenodd'

A string that defines how the inside of a shape is determined.

classNamestring

Custom class name set on an element. Only for SVG renderer. Applied when the element is created; setStyle does not update it afterwards.

rendererRenderer

Use this specific instance of Renderer for this path. If not set, the path uses the map's renderer (SVG by default), or in a custom pane, a renderer of the same kind created for that pane. If set, it overrides the pane option.

dashSpeednumber0

Animates the dashes of the dashArray along the path ("marching ants"), e.g. to show the direction of a flow: the speed in pixels per second, negative for the opposite direction. Not animated with reduced motion.

Added by the optional module maplair/dash-animation.

arrowheadsboolean|{size?: number, repeat?: number, color?: string}false

Arrowheads along a polyline: true for one at the end of each line, or an object with the size (in pixels, default 10), repeat (an arrowhead every that many pixels instead) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

textstring|{content: string, repeat?: boolean, center?: boolean, offset?: number, fontSize?: number, color?: string}|nullnull

Text along a polyline, e.g. a street name: the text, or an object with the content, repeat (repeat the text along the whole line), center (center it on the line), offset (in pixels, perpendicular to the line), fontSize (in pixels, default 12) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from CircleMarker
EventDataDescription
moveCircleMarkerMoveEventFired when the marker is moved via setLatLng. Old and new coordinates are included in event arguments as oldLatLng, latlng.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
getBounds()LatLngBounds

Returns the LatLngBounds of the path. When the circle isn't on a map, they're approximated on a sphere.

Methods inherited from CircleMarker
MethodReturnsDescription
setLatLng(latlng: LatLngExpression)this

Sets the position of a circle marker to a new location.

getLatLng()LatLng

Returns the current geographical position of the circle marker.

setRadius(radius: number)this

Sets the radius of a circle marker. Units are in CSS pixels.

getRadius()number

Returns the current radius of the circle. Units are in CSS pixels.

setStyle(options: CircleMarkerOptions)this

Changes the appearance of the circle marker, also its radius.

toGeoJSON(precision?: number | false)Feature

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the circle marker (as a GeoJSON Point Feature).

Methods inherited from Path
MethodReturnsDescription
beforeAdd(map: MaplairMap)void

Gets the renderer of the path from the map, before it is added.

onAdd()void

Adds the path to its renderer.

onRemove()void

Removes the path from its renderer.

redraw()this

Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.

bringToFront()this

Brings the layer to the top of all path layers.

bringToBack()this

Brings the layer to the bottom of all path layers.

getElement()SVGPathElement | undefined

Returns the SVG path element of the layer, if it is rendered by the SVG renderer.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

CircleMarker extends Path

A circle of a fixed size with radius specified in CSS pixels. Extends Path.

Constructor

ConstructorDescription
new CircleMarker(latlng: LatLngExpression, options?: CircleMarkerOptions)

Instantiates a circle marker object given a geographical point, and an optional options object.

Options

OptionTypeDefaultDescription
fillbooleantrue

Whether to fill the circle with color.

radiusnumber10

Radius of the circle marker, in CSS pixels.

displaceboolean

Whether to include this marker in the displacement of the map, see DisplaceHandler.

displaceIdstring

Stable identifier shared across marker instances that represent the same thing on different layers, so that DisplaceHandler puts them at the same displaced position.

Options inherited from Path
OptionTypeDefaultDescription
strokebooleantrue

Whether to draw stroke along the path. Set it to false to disable borders on polygons or circles.

colorstring'#3388ff'

Stroke color.

weightnumber3

Stroke width in pixels.

opacitynumber1

Stroke opacity.

lineCapstring'round'

A string that defines shape to be used at the end of the stroke.

lineJoinstring'round'

A string that defines shape to be used at the corners of the stroke.

dashArraystring|nullnull

A string that defines the stroke dash pattern.

dashOffsetstring|nullnull

A string that defines the distance into the dash pattern to start the dash.

fillbooleanfalse

Whether to fill the path with color. Set it to false to disable filling on polygons or circles. The default depends on the class: true for polygons and circles.

fillColorstring|nullnull

Fill color. Defaults to the value of the color option.

fillOpacitynumber0.2

Fill opacity.

fillRulestring'evenodd'

A string that defines how the inside of a shape is determined.

classNamestring

Custom class name set on an element. Only for SVG renderer. Applied when the element is created; setStyle does not update it afterwards.

rendererRenderer

Use this specific instance of Renderer for this path. If not set, the path uses the map's renderer (SVG by default), or in a custom pane, a renderer of the same kind created for that pane. If set, it overrides the pane option.

dashSpeednumber0

Animates the dashes of the dashArray along the path ("marching ants"), e.g. to show the direction of a flow: the speed in pixels per second, negative for the opposite direction. Not animated with reduced motion.

Added by the optional module maplair/dash-animation.

arrowheadsboolean|{size?: number, repeat?: number, color?: string}false

Arrowheads along a polyline: true for one at the end of each line, or an object with the size (in pixels, default 10), repeat (an arrowhead every that many pixels instead) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

textstring|{content: string, repeat?: boolean, center?: boolean, offset?: number, fontSize?: number, color?: string}|nullnull

Text along a polyline, e.g. a street name: the text, or an object with the content, repeat (repeat the text along the whole line), center (center it on the line), offset (in pixels, perpendicular to the line), fontSize (in pixels, default 12) and color (default: the color of the path).

Added by the optional module maplair/path-decorations.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
moveCircleMarkerMoveEventFired when the marker is moved via setLatLng. Old and new coordinates are included in event arguments as oldLatLng, latlng.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
setLatLng(latlng: LatLngExpression)this

Sets the position of a circle marker to a new location.

getLatLng()LatLng

Returns the current geographical position of the circle marker.

setRadius(radius: number)this

Sets the radius of a circle marker. Units are in CSS pixels.

getRadius()number

Returns the current radius of the circle. Units are in CSS pixels.

setStyle(options: CircleMarkerOptions)this

Changes the appearance of the circle marker, also its radius.

toGeoJSON(precision?: number | false)Feature

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the circle marker (as a GeoJSON Point Feature).

Methods inherited from Path
MethodReturnsDescription
beforeAdd(map: MaplairMap)void

Gets the renderer of the path from the map, before it is added.

onAdd()void

Adds the path to its renderer.

onRemove()void

Removes the path from its renderer.

redraw()this

Redraws the layer. Sometimes useful after you changed the coordinates that the path uses.

bringToFront()this

Brings the layer to the top of all path layers.

bringToBack()this

Brings the layer to the bottom of all path layers.

getElement()SVGPathElement | undefined

Returns the SVG path element of the layer, if it is rendered by the SVG renderer.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

SVG extends Renderer

Allows vector layers to be displayed with SVG. Inherits Renderer.

Usage example

Use SVG by default for all paths in the map:

const map = new MaplairMap('map', {
	renderer: new SVG()
});

Use a SVG renderer with extra padding for specific vector geometries:

const map = new MaplairMap('map');
const myRenderer = new SVG({ padding: 0.5 });
const line = new Polyline( coordinates, { renderer: myRenderer } );
const circle = new Circle( center, { renderer: myRenderer, radius: 100 } );

Events

Events inherited from Renderer
EventDataDescription
updateMaplairEventFired when the renderer updates its bounds, center and zoom, for example when its map has moved.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Methods inherited from Renderer
MethodReturnsDescription
onRemove()void

Removes the container of the renderer from the map.

Methods inherited from BlanketOverlay
MethodReturnsDescription
onAdd(map: MaplairMap)void
getEvents()Record<string, EventListener>

Returns the map events the blanket listens to.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Static members

MethodReturnsDescription
create(name: string)SVGElement

Returns a instance of SVGElement, corresponding to the class name passed. For example, using 'line' will return an instance of SVGLineElement.

pointsToPath(rings: Point[][], closed?: boolean)string

Generates a SVG path string for multiple rings, with each ring turning into "M..L..L.." instructions.

Canvas extends Renderer

Allows vector layers to be displayed with <canvas>. Inherits Renderer.

Usage example

Use Canvas by default for all paths in the map:

const map = new MaplairMap('map', {
	renderer: new Canvas()
});

Use a Canvas renderer with extra padding for specific vector geometries:

const map = new MaplairMap('map');
const myRenderer = new Canvas({ padding: 0.5 });
const line = new Polyline( coordinates, { renderer: myRenderer } );
const circle =  new Circle( center, { renderer: myRenderer, radius: 100 } );

Constructor

ConstructorDescription
new Canvas(options?: CanvasOptions | undefined)

Creates a Canvas renderer with the given options.

Options

OptionTypeDefaultDescription
tolerancenumber0

How much to extend the click tolerance around a path/object on the map.

Options inherited from BlanketOverlay
OptionTypeDefaultDescription
paddingnumber0.1

How 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.

continuousbooleanfalse

When false, the blanket will update its position only when the map state settles (after a pan/zoom animation). When true, it will update when the map state changes (during pan/zoom animations).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from Renderer
EventDataDescription
updateMaplairEventFired when the renderer updates its bounds, center and zoom, for example when its map has moved.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Methods inherited from Renderer
MethodReturnsDescription
onRemove()void

Removes the container of the renderer from the map.

Methods inherited from BlanketOverlay
MethodReturnsDescription
onAdd(map: MaplairMap)void
getEvents()Record<string, EventListener>

Returns the map events the blanket listens to.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

LayerGroup extends Layer

Used to group several layers and handle them as one. If you add it to the map, any layers added or removed from the group will be added/removed on the map as well. Extends Layer.

Usage example

new LayerGroup([marker1, marker2])
	.addLayer(polyline)
	.addTo(map);

Constructor

ConstructorDescription
new LayerGroup(layers?: Layer[], options?: InteractiveLayerOptions)

Creates a layer group, optionally given an initial set of layers and an options object.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
addLayer(layer: Layer)this

Adds the given layer to the group.

removeLayer(layer: Layer | number)this

Removes the given layer, or the layer with the given internal ID, from the group.

hasLayer(layer: Layer | number)boolean

Returns true if the given layer, or the layer with the given internal ID, is currently added to the group.

clearLayers()this

Removes all the layers from the group.

onAdd(map: MaplairMap)void

Adds the layers of the group to the map.

onRemove(map: MaplairMap)void

Removes the layers of the group from the map.

eachLayer(method: (layer: Layer) => void, context?: object)this

Iterates over the layers of the group, optionally specifying context of the iterator function.

group.eachLayer(layer => layer.bindPopup('Hello'));
getLayer(id: number)Layer | undefined

Returns the layer with the given internal ID.

getLayers()Layer[]

Returns an array of all the layers added to the group.

setZIndex(zIndex: number)this

Calls setZIndex on every layer contained in this group, passing the z-index.

getLayerId(layer: Layer)number

Returns the internal ID for a layer.

toGeoJSON(precision?: number | false)Feature | FeatureCollection

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the layer group (as a GeoJSON FeatureCollection, GeometryCollection, or MultiPoint).

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

FeatureGroup extends LayerGroup

Extended LayerGroup that makes it easier to do the same thing to all its member layers:

  • bindPopup binds a popup to all of the layers at once (likewise with bindTooltip)
  • Events are propagated to the FeatureGroup, so if the group has an event handler, it will handle events from any of the layers. This includes pointer events and custom events.
  • Has layeradd and layerremove events

Usage example

new FeatureGroup([marker1, marker2, polyline])
	.bindPopup('Hello world!')
	.on('click', function() { alert('Clicked on a member of the group!'); })
	.addTo(map);

Events

EventDataDescription
layeraddLayerEventFired when a layer is added to this FeatureGroup.
layerremoveLayerEventFired when a layer is removed from this FeatureGroup.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
addLayer(layer: Layer)this

Adds the given layer to the group.

removeLayer(layer: Layer | number)this

Removes the given layer, or the layer with the given internal ID, from the group.

setStyle(style: PathOptions)this

Sets the given path options to each layer of the group that has a setStyle method.

setInteractive(interactive: boolean)this

Changes the interactive option of each layer of the group.

bringToFront()this

Brings the layer group to the top of all other layers.

bringToBack()this

Brings the layer group to the back of all other layers.

getBounds()LatLngBounds

Returns the LatLngBounds of the feature group (created from bounds and coordinates of its children, including the layers of nested layer groups).

Methods inherited from LayerGroup
MethodReturnsDescription
hasLayer(layer: Layer | number)boolean

Returns true if the given layer, or the layer with the given internal ID, is currently added to the group.

clearLayers()this

Removes all the layers from the group.

onAdd(map: MaplairMap)void

Adds the layers of the group to the map.

onRemove(map: MaplairMap)void

Removes the layers of the group from the map.

eachLayer(method: (layer: Layer) => void, context?: object)this

Iterates over the layers of the group, optionally specifying context of the iterator function.

group.eachLayer(layer => layer.bindPopup('Hello'));
getLayer(id: number)Layer | undefined

Returns the layer with the given internal ID.

getLayers()Layer[]

Returns an array of all the layers added to the group.

setZIndex(zIndex: number)this

Calls setZIndex on every layer contained in this group, passing the z-index.

getLayerId(layer: Layer)number

Returns the internal ID for a layer.

toGeoJSON(precision?: number | false)Feature | FeatureCollection

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the layer group (as a GeoJSON FeatureCollection, GeometryCollection, or MultiPoint).

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

GeoJSON extends FeatureGroup

Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse GeoJSON data and display it on the map. Extends FeatureGroup.

There are several static functions which can be called without instantiating GeoJSON.

Usage example

new GeoJSON(data, {
	style: function (feature) {
		return {color: feature.properties.color};
	}
}).bindPopup(function (layer) {
	return layer.feature.properties.description;
}).addTo(map);

Constructor

ConstructorDescription
new GeoJSON(geojson?: GeoJSONData | GeoJSONData[] | null, options?: GeoJSONOptions)

Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format to display on the map (you can alternatively add it later with addData method) and an options object.

Options

OptionTypeDefaultDescription
pointToLayer(geoJsonPoint: Feature, latlng: LatLng) => Layer

A Function defining how GeoJSON points spawn Maplair layers. It is internally called when data is added, passing the GeoJSON point feature and its LatLng. The default is to spawn a default Marker:

function(geoJsonPoint, latlng) {
return new Marker(latlng);
}
stylePathOptions|((geoJsonFeature: Feature) => PathOptions)

A Function defining the Path options for styling GeoJSON lines and polygons, called internally when data is added. The default value is to not override any defaults:

function (geoJsonFeature) {
return {}
}
onEachFeature(feature: Feature, layer: Layer) => void

A Function that will be called once for each created Feature, after it has been created and styled. Useful for attaching events and popups to features. It will receive the feature as the first argument and its corresponding spawned layer from asFeature as the second. The default is to do nothing with the newly created layers:

function (feature, layer) {}
filter(geoJsonFeature: Feature) => boolean

A Function that will be used to decide whether to include a feature or not. The default is to include all features:

function (geoJsonFeature) {
return true;
}

Note: dynamically changing the filter option will have effect only on newly added data. It will not re-evaluate already included features.

coordsToLatLng(coords: number[]) => LatLng

A Function that will be used for converting GeoJSON coordinates to LatLngs. The default is the coordsToLatLng static method.

markersInheritOptionsbooleanfalse

Whether default Markers for "Point" type Features inherit from group options.

urlstringundefined

A URL to load the GeoJSON data from when creating the layer.

Added by the optional module maplair/geojson-loading.

fetchOptionsRequestInitundefined

Options for fetch() when loading, e.g. {headers: {Authorization: 'Bearer …'}}.

Added by the optional module maplair/geojson-loading.

fitBoundsbooleanfalse

Whether to fit the map to the bounds of the data once loaded.

Added by the optional module maplair/geojson-loading.

Options inherited from InteractiveLayerOptions
OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
loadingMaplairEventFired when starting to load data with load(). (maplair/geojson-loading)
loadGeoJSONLoadEventFired when the data of load() has been added, with the data. (maplair/geojson-loading)
errorGeoJSONLoadErrorEventFired when load() fails, with the error. (maplair/geojson-loading)
Events inherited from FeatureGroup
EventDataDescription
layeraddLayerEventFired when a layer is added to this FeatureGroup.
layerremoveLayerEventFired when a layer is removed from this FeatureGroup.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Loading GeoJSON

MethodReturnsDescription
load(source: string | Promise<GeoJsonObject | GeoJsonObject[]>, fetchOptions?: RequestInit)Promise<this>

Loads GeoJSON data from a URL (or a promise of the data) and replaces the layers with it. A running load is aborted. Returns a promise of this layer.

fetchOptions
Defaults to the fetchOptions option.

Added by the optional module maplair/geojson-loading.

Other methods

MethodReturnsDescription
addData(geojson: GeoJSONData | GeoJSONData[])this

Adds a GeoJSON object to the layer.

resetStyle(layer?: Layer)this

Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events. If layer is omitted, the style of all features in the current layer is reset.

setStyle(style: PathOptions | ((geoJsonFeature: Feature) => PathOptions))this

Changes styles of GeoJSON vector layers with the given style function.

Methods inherited from FeatureGroup
MethodReturnsDescription
addLayer(layer: Layer)this

Adds the given layer to the group.

removeLayer(layer: Layer | number)this

Removes the given layer, or the layer with the given internal ID, from the group.

setInteractive(interactive: boolean)this

Changes the interactive option of each layer of the group.

bringToFront()this

Brings the layer group to the top of all other layers.

bringToBack()this

Brings the layer group to the back of all other layers.

getBounds()LatLngBounds

Returns the LatLngBounds of the feature group (created from bounds and coordinates of its children, including the layers of nested layer groups).

Methods inherited from LayerGroup
MethodReturnsDescription
hasLayer(layer: Layer | number)boolean

Returns true if the given layer, or the layer with the given internal ID, is currently added to the group.

clearLayers()this

Removes all the layers from the group.

onAdd(map: MaplairMap)void

Adds the layers of the group to the map.

onRemove(map: MaplairMap)void

Removes the layers of the group from the map.

eachLayer(method: (layer: Layer) => void, context?: object)this

Iterates over the layers of the group, optionally specifying context of the iterator function.

group.eachLayer(layer => layer.bindPopup('Hello'));
getLayer(id: number)Layer | undefined

Returns the layer with the given internal ID.

getLayers()Layer[]

Returns an array of all the layers added to the group.

setZIndex(zIndex: number)this

Calls setZIndex on every layer contained in this group, passing the z-index.

getLayerId(layer: Layer)number

Returns the internal ID for a layer.

toGeoJSON(precision?: number | false)Feature | FeatureCollection

Coordinates values are rounded with formatNum to the given precision. Returns a GeoJSON representation of the layer group (as a GeoJSON FeatureCollection, GeometryCollection, or MultiPoint).

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getEvents()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Static members

MethodReturnsDescription
geometryToLayer(geojson: GeoJsonObject, options?: GeoJSONOptions)Layer | null

Creates a Layer from a given GeoJSON feature. Can use a custom pointToLayer and/or coordsToLatLng functions if provided as options.

coordsToLatLng(coords: number[])LatLng

Creates a LatLng object from an array of 2 numbers (longitude, latitude) or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points.

coordsToLatLngs(coords: any[], levelsDeep?: number, _coordsToLatLng?: (coords: number[]) => LatLng)any[]

Creates a multidimensional array of LatLngs from a GeoJSON coordinates array. levelsDeep specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default). Can use a custom coordsToLatLng function.

latLngToCoords(latlng: LatLngExpression, precision?: number | false)number[]

Reverse of coordsToLatLng. Coordinates values are rounded with formatNum function.

latLngsToCoords(latlngs: any[], levelsDeep?: number, close?: boolean, precision?: number | false)any[]

Reverse of coordsToLatLngs. close determines whether the first point should be appended to the end of the array to close the feature, only used when levelsDeep is 0. False by default. Coordinates values are rounded with formatNum function.

getFeature(layer: Layer, newGeometry: Geometry)Feature

Returns GeoJSON geometries/features of layer with new GeoJSON geometry.

asFeature(geojson: GeoJsonObject)Feature | FeatureCollection

Normalize GeoJSON geometries/features into GeoJSON features.

Classification

Classifies features by the value of an attribute, for thematic maps: each class has a symbol (path options such as fillColor) and a legend label. A class is either given by value ({value: 'S2'}, or several values sharing one class {value: ['S1', 'S2']}) or by range ({lower: 0, upper: 10} for 0 ≤ value < 10, either bound left out for an open end); both kinds may be mixed in one classification. A feature is classified by its exact value first, then by range, then by legend label, else it falls into the otherValues class.

Use style as style option of GeoJSON to style the features by their class, and LegendControl.addClassification() to show the classes in a legend, with the feature count per class.

Usage example

const temperature = new Classification([
	{value: null, symbol: {fillColor: '#000000'}, legend: 'No data', counted: false},
	{upper: 0, symbol: {fillColor: '#5bc0de'}, legend: '< 0 °C'},
	{lower: 0, upper: 10, symbol: {fillColor: '#33ee33'}, legend: '0–10 °C'},
	{lower: 10, symbol: {fillColor: '#f0a030'}, legend: '≥ 10 °C'}
], {name: 'Air temperature', value: 'temperature'});

const stations = new GeoJSON(data, {
	pointToLayer: (feature, latlng) => new CircleMarker(latlng, {color: '#ffffff'}),
	style: temperature.style
}).addTo(map);

temperature.classify(data.features[0]).legend; // e.g. '0–10 °C'

Inspired by the categorized and graduated renderers of QGIS.

Constructor

ConstructorDescription
new Classification(classes: ClassificationClass[], options?: ClassificationOptions)

Creates a classification from the given classes. Each class is an object with value (a value or an array of values) or lower/upper (a range including lower, excluding upper), a symbol (path options), a legend label, and counted: false to exclude the class from the feature count (e.g. "no data").

Options

OptionTypeDefaultDescription
namestring''

The name of the classification, shown as title of its legend.

valuestring|((feature: any) => any)

The value to classify by: the name of a property of the feature, or a function receiving the feature and returning the value. Without it, the argument of classify() is the value itself.

normalize(value: any) => any

A function applied to the values of the classes and of the features before comparing them, for tolerant matching, e.g. v => String(v).trim().toUpperCase().

otherValuesClassificationClass

The class of all values not matching any other class, with symbol and legend (default "All other values"). Without it, such features are not classified.

Methods

MethodReturnsDescription
style(feature: any)PathOptions

Returns the symbol of the class of the feature (an empty object for features without class), bound to the classification for the style option of GeoJSON.

feature
A Feature, a Layer with a feature, or a value.
classify(feature: any)ClassificationClass | undefined

Returns the class of the given GeoJSON feature, of a layer with a feature (as created by GeoJSON) or, without the value option, of a value: one of the classes passed to the constructor, the otherValues class or undefined.

feature
A Feature, a Layer with a feature, or a value.
legendItems()ClassificationLegendItem[]

Returns the items of the legend, {legend, symbol, counted, classes}, in the order of the classes and otherValues last. Classes with the same legend label and symbol share one item.

featureCount(features: any[])ClassificationFeatureCount[]

Counts the given features (or layers with a feature) per legend item, returning the legend items with count and share (the fraction of the counted features). Classes with counted: false get a count, but no share, and do not count toward the total.

features
Features, Layers with a feature, or values.

Static members

MethodReturnsDescription
quantile(values: number[], n: number){ lower?: number; upper?: number; }[]

Returns n ranges {lower, upper} with about the same number of the given values each (fewer for repeated values), the first and last range open-ended. Add a symbol (and a legend) to each to create a Classification.

equalInterval(values: number[], n: number){ lower?: number; upper?: number; }[]

Returns n ranges {lower, upper} of equal width between the minimum and the maximum of the given values, the first and last range open-ended.

GridLayer extends Layer

Generic class for handling a tiled grid of HTML elements, and the base class of all tile layers. To show map tiles from a URL, use TileLayer (or WMSTileLayer). Extend GridLayer to create a tiled grid of your own elements like <canvas>, <img> or <div>; it handles creating and animating them for you.

Layers extending GridLayer shall reimplement the createTile() method.

Usage example

Synchronous usage

To create a custom layer, extend GridLayer and implement the createTile() method, which will be passed a Point object with the x, y, and z (zoom level) coordinates to draw your tile.

class CanvasLayer extends GridLayer {
    createTile(coords) {
        // create a <canvas> element for drawing
        const tile = DomUtil.create('canvas', 'maplair-tile');

        // setup tile width and height according to the options
        const size = this.getTileSize();
        tile.width = size.x;
        tile.height = size.y;

        // get a canvas context and draw something on it using coords.x, coords.y and coords.z
        const ctx = tile.getContext('2d');

        // return the tile so it can be rendered on screen
        return tile;
    }
}

Asynchronous usage

Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the done() callback.

class CanvasLayer extends GridLayer {
    createTile(coords, done) {
        const error;

        // create a <canvas> element for drawing
        const tile = DomUtil.create('canvas', 'maplair-tile');

        // setup tile width and height according to the options
        const size = this.getTileSize();
        tile.width = size.x;
        tile.height = size.y;

        // draw something asynchronously and pass the tile to the done() callback
        setTimeout(function() {
            done(error, tile);
        }, 1000);

        return tile;
    }
}

Constructor

ConstructorDescription
new GridLayer(options?: GridLayerOptions)

Creates a new instance of GridLayer with the supplied options.

Options

OptionTypeDefaultDescription
tileSizenumber|Point256

Width and height of tiles in the grid. Use a number if width and height are equal, or Point(width, height) otherwise.

opacitynumber1

Opacity of the tiles. Can be used in the createTile() function.

placeholderstring|nullnull

A CSS background shown in place of tiles while they are loading, e.g. '#ddd' or 'url(loading.svg) center no-repeat #eee'. Tiles with a placeholder appear without fading in.

updateWhenIdlebooleanfalse

Load new tiles only when panning ends.

updateWhenZoomingbooleantrue

By default, a smooth zoom animation (during a pinch zoom or a flyTo()) will update grid layers every integer zoom level. Setting this option to false will update the grid layer only when the smooth animation ends.

updateIntervalnumber200

Tiles will not update more than once every updateInterval milliseconds when panning.

zIndexnumber1

The explicit zIndex of the tile layer.

boundsLatLngBoundsExpression|nullnull

If set, tiles will only be loaded inside the set LatLngBounds.

minZoomnumber0

The minimum zoom level down to which this layer will be displayed (inclusive).

maxZoomnumber

The maximum zoom level up to which this layer will be displayed (inclusive).

maxNativeZoomnumber

Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than maxNativeZoom will be loaded from maxNativeZoom level and auto-scaled.

minNativeZoomnumber

Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than minNativeZoom will be loaded from minNativeZoom level and auto-scaled.

noWrapbooleanfalse

Whether the layer is wrapped around the antimeridian. If true, the GridLayer will only be displayed once at low zoom levels. Has no effect when the map CRS doesn't wrap around. Can be used in combination with bounds to prevent requesting tiles outside the CRS limits.

panestring'tilePane'

Map pane where the grid layer will be added.

classNamestring''

A custom class name to assign to the tile layer. Empty by default.

pixelatedbooleanfalse

Whether to scale the tiles with nearest-neighbour interpolation (image-rendering: pixelated) instead of smoothing them, so that their pixels stay crisp, e.g. while zooming or beyond maxNativeZoom. Useful for raster data, pixel art or scientific imagery.

keepBuffernumber2

When panning the map, keep this many rows and columns of tiles before unloading them.

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
loadingMaplairEventFired when the grid layer starts loading tiles.
tileunloadTileEventFired when a tile is removed (e.g. when a tile goes off the screen).
tileloadstartTileEventFired when a tile is requested and starts loading.
tileerrorTileErrorEventFired when there is an error loading a tile.
tileloadTileEventFired when a tile loads.
loadMaplairEventFired when the grid layer loaded all visible tiles.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Extension methods

MethodReturnsDescription
createTile(coords: Point, done?: TileDoneCallback | undefined)HTMLElement

Called only internally, must be overridden by classes extending GridLayer. Returns the HTMLElement corresponding to the given coords. If the done callback is specified, it must be called when the tile has finished loading and drawing.

Other methods

MethodReturnsDescription
onAdd(map: MaplairMap)void

Creates the container of the tiles and loads the tiles.

beforeAdd(map: MaplairMap)void

Registers the zoom limits of the layer on the map.

onRemove(map: MaplairMap)void

Removes the tiles from the map.

bringToFront()this

Brings the tile layer to the top of all tile layers.

bringToBack()this

Brings the tile layer to the bottom of all tile layers.

getContainer()HTMLElement

Returns the HTML element that contains the tiles for this layer.

setOpacity(opacity: number)this

Changes the opacity of the grid layer.

setZIndex(zIndex: number)this

Changes the zIndex of the grid layer.

isLoading()boolean

Returns true if any tile in the grid layer has not finished loading.

redraw()this

Causes the layer to clear all the tiles and request them again.

getEvents()Record<string, Function>

Returns the map events the layer listens to, see Layer.

getTileSize()Point

Normalizes the tileSize option into a point. Used by the createTile() method.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

LatLng

Represents a geographical point with a certain latitude and longitude.

Usage example

const latlng = new LatLng(50.5, 30.5);

All Maplair methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent:

map.panTo([50, 30]);
map.panTo({lat: 50, lng: 30});
map.panTo({lat: 50, lon: 30});
map.panTo(new LatLng(50, 30));

Note that LatLng does not inherit from Maplair's Class object, which means new classes can't inherit from it, and new methods can't be added to it with the include function.

Constructor

ConstructorDescription
new LatLng(lat: number | LatLngExpression, lng?: number, alt?: number)

Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude). Alternatively, expects a LatLng object, an array of the form [lat, lng] or [lat, lng, alt], or a plain object of the form {lat, lng} or {lat, lng, alt} (lon can be used in place of lng) instead.

lat
Latitude in degrees, or the coordinates.
lng
Longitude in degrees.
alt
Altitude in meters.

Methods

MethodReturnsDescription
equals(obj: LatLngExpression, maxMargin?: number)boolean

Returns true if the given LatLng point is at the same position (within a small margin of error). The margin of error can be overridden by setting maxMargin to a small number.

toString(precision?: number | false)string

Returns a string representation of the point (for debugging purposes).

distanceTo(other: LatLngExpression)number

Returns the distance (in meters) to the given LatLng calculated using the Haversine formula.

wrap()LatLng

Returns a new LatLng object with the longitude wrapped so it's always between -180 and +180 degrees.

toBounds(sizeInMeters: number)LatLngBounds

Returns a new LatLngBounds object in which each boundary is sizeInMeters/2 meters apart from the LatLng.

Properties

PropertyTypeDescription
latnumber

Latitude in degrees.

lngnumber

Longitude in degrees.

altnumber | undefined

Altitude in meters (optional).

Static members

MethodReturnsDescription
from(lat: number | LatLngExpression, lng?: number, alt?: number)LatLng

Returns the given LatLng object as it is, or else a new LatLng object created from the given arguments (the same as of the constructor) — unlike the constructor, which always creates a new object.

lat
Latitude in degrees, or the coordinates.
lng
Longitude in degrees.
alt
Altitude in meters.
LatLng.from(latlng) === latlng; // true
LatLng.from([50.5, 30.5]); // LatLng(50.5, 30.5)
validate(lat: any, lng?: any, alt?: any)boolean

Returns true if the LatLng object can be properly initialized with the given arguments (the same as of the constructor).

parse(text: string)LatLng | null

Parses coordinates in decimal degrees: a pair of numbers (latitude first), e.g. '47.27, 11.4' or '47.27 11.4', with the hemispheres before or after the numbers, e.g. 'N 47.27, E 11.4', '47.27° S 11.4° W' (also longitude first), or a geo URI like 'geo:47.27,11.4' (with an optional altitude). Returns null for other text and out-of-range coordinates.

LatLng.parse('47.2692 N, 11.4041 E'); // LatLng(47.2692, 11.4041)
LatLng.parse('geo:47.2692,11.4041?z=13'); // LatLng(47.2692, 11.4041)

LatLngBounds

Represents a rectangular geographical area on a map.

Usage example

const corner1 = new LatLng(40.712, -74.227),
corner2 = new LatLng(40.774, -74.125),
bounds = new LatLngBounds(corner1, corner2);

All Maplair methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:

map.fitBounds([
	[40.712, -74.227],
	[40.774, -74.125]
]);

Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners outside the [-180, 180] degrees longitude range.

Note that LatLngBounds does not inherit from Maplair's Class object, which means new classes can't inherit from it, and new methods can't be added to it with the include function.

Constructor

ConstructorDescription
new LatLngBounds(corner1?: LatLngExpression | LatLngBoundsExpression, corner2?: LatLngExpression)

Creates a LatLngBounds object by defining two diagonally opposite corners of the rectangle. Alternatively, creates a LatLngBounds object defined by the geographical points it contains (very useful for zooming the map to fit a particular set of locations with fitBounds), or a copy of the given LatLngBounds object.

corner1
The first corner, the points or the bounds to copy.
corner2
The opposite corner.

Methods

MethodReturnsDescription
extend(obj: LatLngExpression | LatLngBoundsExpression)this

Extend the bounds to contain the given point or bounds.

pad(bufferRatio: number)LatLngBounds

Returns bounds created by extending or retracting the current bounds by a given ratio in each direction. For example, a ratio of 0.5 extends the bounds by 50% in each direction. Negative values will retract the bounds.

getCenter()LatLng

Returns the center point of the bounds.

getSouthWest()LatLng

Returns the south-west point of the bounds.

getNorthEast()LatLng

Returns the north-east point of the bounds.

getNorthWest()LatLng

Returns the north-west point of the bounds.

getSouthEast()LatLng

Returns the south-east point of the bounds.

getWest()number

Returns the west longitude of the bounds.

getSouth()number

Returns the south latitude of the bounds.

getEast()number

Returns the east longitude of the bounds.

getNorth()number

Returns the north latitude of the bounds.

contains(obj: LatLngBoundsExpression | LatLngExpression)boolean

Returns true if the rectangle contains the given bounds or point.

intersects(bounds: LatLngBoundsExpression)boolean

Returns true if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.

overlaps(bounds: LatLngBoundsExpression)boolean

Returns true if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.

toBBoxString()string

Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' format. Useful for sending requests to web services that return geo data.

equals(bounds: LatLngBoundsExpression, maxMargin?: number)boolean

Returns true if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting maxMargin to a small number.

isValid()boolean

Returns true if the bounds are properly initialized.

Static members

MethodReturnsDescription
from(corner1?: LatLngExpression | LatLngBoundsExpression, corner2?: LatLngExpression)LatLngBounds

Returns the given LatLngBounds object as it is, or else a new LatLngBounds object created from the given arguments (the same as of the constructor) — unlike the constructor, which always creates a new object.

corner1
The first corner, the points or the bounds.
corner2
The opposite corner.

Point

Represents a point with x and y coordinates in pixels.

Usage example

const point = new Point(200, 300);

All Maplair methods and options that accept Point objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent:

map.panBy([200, 300]);
map.panBy(new Point(200, 300));

Note that Point does not inherit from Maplair's Class object, which means new classes can't inherit from it, and new methods can't be added to it with the include function.

Constructor

ConstructorDescription
new Point(x: number | PointExpression, y?: number, round?: boolean)

Creates a Point object with the given x and y coordinates. If optional round is set to true, rounds the x and y values. Alternatively, expects a Point object, an array of the form [x, y] or a plain object of the form {x, y} instead.

x
The x coordinate, or the coordinates.
y
The y coordinate.

Methods

MethodReturnsDescription
add(point: PointExpression)Point

Returns the result of addition of the current and the given points.

subtract(point: PointExpression)Point

Returns the result of subtraction of the given point from the current.

divideBy(num: number)Point

Returns the result of division of the current point by the given number.

multiplyBy(num: number)Point

Returns the result of multiplication of the current point by the given number.

scaleBy(point: Point)Point

Multiply each coordinate of the current point by each coordinate of scale. In linear algebra terms, multiply the point by the scaling matrix defined by scale.

point
The scale.
unscaleBy(point: Point)Point

Inverse of scaleBy. Divide each coordinate of the current point by each coordinate of scale.

point
The scale.
round()Point

Returns a copy of the current point with rounded coordinates.

floor()Point

Returns a copy of the current point with floored coordinates (rounded down).

ceil()Point

Returns a copy of the current point with ceiled coordinates (rounded up).

trunc()Point

Returns a copy of the current point with truncated coordinates (rounded towards zero).

distanceTo(point: PointExpression)number

Returns the cartesian distance between the current and the given points.

equals(point: PointExpression)boolean

Returns true if the given point has the same coordinates.

contains(point: PointExpression)boolean

Returns true if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values).

toString()string

Returns a string representation of the point for debugging purposes.

Properties

PropertyTypeDescription
xnumber

The x coordinate of the point.

ynumber

The y coordinate of the point.

Static members

MethodReturnsDescription
from(x: number | PointExpression, y?: number, round?: boolean)Point

Returns the given Point object as it is (unless round is set), or else a new Point object created from the given arguments (the same as of the constructor) — unlike the constructor, which always creates a new object.

x
The x coordinate, or the coordinates.
y
The y coordinate.
Point.from(point) === point; // true
Point.from([200, 300]); // Point(200, 300)
validate(x: any, y?: any)boolean

Returns true if the Point object can be properly initialized with the given arguments (the same as of the constructor).

Bounds

Represents a rectangular area in pixel coordinates.

Usage example

const p1 = new Point(10, 10),
p2 = new Point(40, 60),
bounds = new Bounds(p1, p2);

All Maplair methods that accept Bounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this:

otherBounds.intersects([[10, 10], [40, 60]]);

Note that Bounds does not inherit from Maplair's Class object, which means new classes can't inherit from it, and new methods can't be added to it with the include function.

Constructor

ConstructorDescription
new Bounds(a?: PointExpression | BoundsExpression, b?: PointExpression)

Creates a Bounds object from two corners coordinate pairs. Alternatively, creates a Bounds object from the given array of points, or a copy of the given Bounds object.

a
The first corner, the points or the bounds to copy.
b
The opposite corner.

Methods

MethodReturnsDescription
extend(obj: PointExpression | BoundsExpression)this

Extends the bounds to contain the given point or bounds.

getCenter(round?: boolean)Point

Returns the center point of the bounds.

getBottomLeft()Point

Returns the bottom-left point of the bounds.

getTopRight()Point

Returns the top-right point of the bounds.

getTopLeft()Point

Returns the top-left point of the bounds (i.e. this.min).

getBottomRight()Point

Returns the bottom-right point of the bounds (i.e. this.max).

getSize()Point

Returns the size of the given bounds.

contains(obj: BoundsExpression | PointExpression)boolean

Returns true if the rectangle contains the given bounds or point.

intersects(bounds: BoundsExpression)boolean

Returns true if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common.

overlaps(bounds: BoundsExpression)boolean

Returns true if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area.

isValid()boolean

Returns true if the bounds are properly initialized.

pad(bufferRatio: number)Bounds

Returns bounds created by extending or retracting the current bounds by a given ratio in each direction. For example, a ratio of 0.5 extends the bounds by 50% in each direction. Negative values will retract the bounds.

equals(bounds: BoundsExpression)boolean

Returns true if the rectangle is equivalent to the given bounds.

Properties

PropertyTypeDescription
minPoint

The top left corner of the rectangle.

maxPoint

The bottom right corner of the rectangle.

Static members

MethodReturnsDescription
from(a?: PointExpression | BoundsExpression, b?: PointExpression)Bounds

Returns the given Bounds object as it is, or else a new Bounds object created from the given arguments (the same as of the constructor) — unlike the constructor, which always creates a new object.

a
The first corner, the points or the bounds.
b
The opposite corner.

Icon extends Class

Represents an icon to provide when creating a marker.

DefaultIcon extends Icon and is the blue icon Maplair uses for markers by default.

Usage example

const myIcon = new Icon({
    iconUrl: 'my-icon.png',
    iconRetinaUrl: 'my-icon@2x.png',
    iconSize: [38, 95],
    iconAnchor: [22, 94],
    popupAnchor: [-3, -76],
    shadowUrl: 'my-icon-shadow.png',
    shadowRetinaUrl: 'my-icon-shadow@2x.png',
    shadowSize: [68, 95],
    shadowAnchor: [22, 94]
});

new Marker([50.505, 30.57], {icon: myIcon}).addTo(map);

Constructor

ConstructorDescription
new Icon(options?: IconOptions)

Creates an icon instance with the given options.

Options

OptionTypeDefaultDescription
iconUrlstring

(required) The URL to the icon image (absolute or relative to your script path).

iconRetinaUrlstring

The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices.

iconSizePointExpression|number

Size of the icon image in pixels (a number for square icons).

iconAnchorPointExpression

The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.

popupAnchorPointExpression[0, 0]

The coordinates of the point from which popups will "open", relative to the icon anchor.

tooltipAnchorPointExpression[0, 0]

The coordinates of the point from which tooltips will "open", relative to the icon anchor.

shadowUrlstring

The URL to the icon shadow image. If not specified, no shadow image will be created.

shadowRetinaUrlstring

The URL to a retina sized version of the shadow image. Used for Retina screen devices.

shadowSizePointExpression|number

Size of the shadow image in pixels.

shadowAnchorPointExpression

The coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified).

classNamestring

A custom class name to assign to both icon and shadow images. Empty by default.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the icon images. If a String is provided, all images will have their crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values.

Methods

MethodReturnsDescription
createIcon(oldIcon?: HTMLElement)HTMLElement

Called internally when the icon has to be shown, returns a <img> HTML element styled according to the options.

oldIcon
The current element of the icon, to be reused if possible.
createShadow(oldIcon?: HTMLElement)HTMLElement | null

As createIcon, but for the shadow beneath it. Returns null without a shadow.

oldIcon
The current element of the shadow, to be reused if possible.
Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

DefaultIcon extends Icon

A subclass of Icon, represents the icon to use in Markers when no icon is specified, optionally in another color. The maple leaf marker and its shadow are inlined as SVG data URIs, so they work with any bundler and need no image files.

In order to customize the default icon, just change the properties of DefaultIcon.defaultOptions (which is a set of Icon options).

If you want to completely replace the default icon, override the Marker.defaultOptions.icon with your own icon instead.

Constructor

ConstructorDescription
new DefaultIcon(options?: DefaultIconOptions | undefined)

Creates the default icon, optionally with changed options.

Options

OptionTypeDefaultDescription
iconUrlstring

The maple leaf marker, inlined as an SVG data URI.

colorstring|nullnull

Paints the pin in the given CSS color instead of the default red, overriding iconUrl, e.g. new DefaultIcon({color: 'teal'}).

shadowUrlstring

Its shadow, inlined as an SVG data URI.

iconSizePointExpression|number[25, 41]
iconAnchorPointExpression[12, 41]
popupAnchorPointExpression[1, -34]
tooltipAnchorPointExpression[16, -28]
shadowSizePointExpression|number[41, 41]
Options inherited from Icon
OptionTypeDefaultDescription
iconUrlstring

(required) The URL to the icon image (absolute or relative to your script path).

iconRetinaUrlstring

The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices.

iconSizePointExpression|number

Size of the icon image in pixels (a number for square icons).

iconAnchorPointExpression

The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.

popupAnchorPointExpression[0, 0]

The coordinates of the point from which popups will "open", relative to the icon anchor.

tooltipAnchorPointExpression[0, 0]

The coordinates of the point from which tooltips will "open", relative to the icon anchor.

shadowUrlstring

The URL to the icon shadow image. If not specified, no shadow image will be created.

shadowRetinaUrlstring

The URL to a retina sized version of the shadow image. Used for Retina screen devices.

shadowSizePointExpression|number

Size of the shadow image in pixels.

shadowAnchorPointExpression

The coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified).

classNamestring

A custom class name to assign to both icon and shadow images. Empty by default.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the icon images. If a String is provided, all images will have their crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values.

Methods

Methods inherited from Icon
MethodReturnsDescription
createIcon(oldIcon?: HTMLElement)HTMLElement

Called internally when the icon has to be shown, returns a <img> HTML element styled according to the options.

oldIcon
The current element of the icon, to be reused if possible.
createShadow(oldIcon?: HTMLElement)HTMLElement | null

As createIcon, but for the shadow beneath it. Returns null without a shadow.

oldIcon
The current element of the shadow, to be reused if possible.
Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

DivIcon extends Icon

Represents a lightweight icon for markers that uses a simple <div> element instead of an image. Inherits from Icon but ignores the iconUrl and shadow options.

By default, it has a 'maplair-div-icon' CSS class and is styled as a little white square with a shadow.

Usage example

const myIcon = new DivIcon({className: 'my-div-icon'});
// you can set .my-div-icon styles in CSS

new Marker([50.505, 30.57], {icon: myIcon}).addTo(map);

Constructor

ConstructorDescription
new DivIcon(options?: DivIconOptions | undefined)

Creates a DivIcon instance with the given options.

Options

OptionTypeDefaultDescription
iconSizePointExpression|number[12, 12]

Size of the icon in pixels, also can be set through CSS.

htmlstring|HTMLElement|falsefalse

Custom HTML code to put inside the div element, empty by default. Alternatively, an instance of HTMLElement.

bgPosPointExpression|nullnull

Optional relative position of the background, in pixels.

classNamestring'maplair-div-icon'
Options inherited from Icon
OptionTypeDefaultDescription
iconUrlstring

(required) The URL to the icon image (absolute or relative to your script path).

iconRetinaUrlstring

The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices.

iconSizePointExpression|number

Size of the icon image in pixels (a number for square icons).

iconAnchorPointExpression

The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.

popupAnchorPointExpression[0, 0]

The coordinates of the point from which popups will "open", relative to the icon anchor.

tooltipAnchorPointExpression[0, 0]

The coordinates of the point from which tooltips will "open", relative to the icon anchor.

shadowUrlstring

The URL to the icon shadow image. If not specified, no shadow image will be created.

shadowRetinaUrlstring

The URL to a retina sized version of the shadow image. Used for Retina screen devices.

shadowSizePointExpression|number

Size of the shadow image in pixels.

shadowAnchorPointExpression

The coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified).

classNamestring

A custom class name to assign to both icon and shadow images. Empty by default.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the icon images. If a String is provided, all images will have their crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values.

Methods

MethodReturnsDescription
createShadow()null

Returns null, a DivIcon has no shadow.

Methods inherited from Icon
MethodReturnsDescription
createIcon(oldIcon?: HTMLElement)HTMLElement

Called internally when the icon has to be shown, returns a <img> HTML element styled according to the options.

oldIcon
The current element of the icon, to be reused if possible.
Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

SvgIcon extends DefaultIcon

A marker icon in the shape of the default marker (with its shadow), drawn as inline SVG in any color and with an optional glyph – a character, an emoji or an SVG path (e.g. of an icon set) – instead of the white maple leaf. No image per color is needed, and it stays sharp on any screen.

Inspired by the Leaflet.awesome-markers, leaflet-color-markers and Leaflet.ExtraMarkers plugins.

Usage example

new Marker([47.27, 11.40], {icon: new SvgIcon({color: '#2a81cb', glyph: 'P'})}).addTo(map);
new Marker([47.28, 11.41], {icon: new SvgIcon({color: 'green', glyph: '🚲'})}).addTo(map);
// a 24×24 SVG path, e.g. from Material Design Icons
new Marker([47.29, 11.42], {icon: new SvgIcon({color: 'purple', glyphPath: 'M12 2L2 22h20z'})}).addTo(map);

Constructor

ConstructorDescription
new SvgIcon(options?: SvgIconOptions | undefined)

Creates an SvgIcon with the given options.

Options

OptionTypeDefaultDescription
colorstring'#d4462c'

The fill color of the marker, any CSS color. The outline is a darker shade of it.

glyphstring

A character or emoji (or short text) shown in the marker instead of the maple leaf.

glyphPathstring

The path data of an SVG glyph in a 24×24 view box (like Material Design Icons), shown in the marker instead of the maple leaf.

glyphColorstring'white'

The color of the glyph or the maple leaf.

Options inherited from DefaultIcon
OptionTypeDefaultDescription
iconUrlstring

The maple leaf marker, inlined as an SVG data URI.

colorstring|nullnull

Paints the pin in the given CSS color instead of the default red, overriding iconUrl, e.g. new DefaultIcon({color: 'teal'}).

shadowUrlstring

Its shadow, inlined as an SVG data URI.

iconSizePointExpression|number[25, 41]
iconAnchorPointExpression[12, 41]
popupAnchorPointExpression[1, -34]
tooltipAnchorPointExpression[16, -28]
shadowSizePointExpression|number[41, 41]
Options inherited from Icon
OptionTypeDefaultDescription
iconUrlstring

(required) The URL to the icon image (absolute or relative to your script path).

iconRetinaUrlstring

The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices.

iconSizePointExpression|number

Size of the icon image in pixels (a number for square icons).

iconAnchorPointExpression

The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins.

popupAnchorPointExpression[0, 0]

The coordinates of the point from which popups will "open", relative to the icon anchor.

tooltipAnchorPointExpression[0, 0]

The coordinates of the point from which tooltips will "open", relative to the icon anchor.

shadowUrlstring

The URL to the icon shadow image. If not specified, no shadow image will be created.

shadowRetinaUrlstring

The URL to a retina sized version of the shadow image. Used for Retina screen devices.

shadowSizePointExpression|number

Size of the shadow image in pixels.

shadowAnchorPointExpression

The coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified).

classNamestring

A custom class name to assign to both icon and shadow images. Empty by default.

crossOriginboolean|stringfalse

Whether the crossOrigin attribute will be added to the icon images. If a String is provided, all images will have their crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values.

Methods

Methods inherited from Icon
MethodReturnsDescription
createIcon(oldIcon?: HTMLElement)HTMLElement

Called internally when the icon has to be shown, returns a <img> HTML element styled according to the options.

oldIcon
The current element of the icon, to be reused if possible.
createShadow(oldIcon?: HTMLElement)HTMLElement | null

As createIcon, but for the shadow beneath it. Returns null without a shadow.

oldIcon
The current element of the shadow, to be reused if possible.
Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

ZoomControl extends Control

A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its zoomControl option to false.

Constructor

ConstructorDescription
new ZoomControl(options?: ZoomControlOptions)

Creates a zoom control.

Options

OptionTypeDefaultDescription
positionstring'topleft'

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

zoomInTextstring

The HTML of the 'zoom in' button, a plus sign drawn in SVG by default.

zoomOutTextstring

The HTML of the 'zoom out' button, a minus sign drawn in SVG by default.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
disable()this

Disables the zoom buttons.

enable()this

Enables the zoom buttons (if the zoom level allows).

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

AttributionControl extends Control

The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its attributionControl option to false, and it fetches attribution texts from layers with the getAttribution method automatically.

Constructor

ConstructorDescription
new AttributionControl(options?: AttributionControlOptions)

Creates an attribution control.

Options

OptionTypeDefaultDescription
positionstring'bottomright'

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

prefixstring|false|nullnull

The HTML text shown before the attributions. Pass false to disable. By default (null), a link to Maplair.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
setPrefix(prefix: string | false)this

The HTML text shown before the attributions. Pass false to disable.

addAttribution(text: string, order?: number)this

Adds an attribution text (e.g. '© OpenStreetMap contributors'). Attributions are sorted by order (see the layer option attributionOrder), then by the order of adding.

removeAttribution(text: string)this

Removes an attribution text.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

LayersControl extends Control

The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the detailed example).

Usage example

const baseLayers = {
	"Mapbox": mapbox,
	"OpenStreetMap": osm
};

const overlays = {
	"Marker": marker,
	"Roads": roadsLayer
};

new LayersControl(baseLayers, overlays).addTo(map);

The baseLayers and overlays parameters are object literals with layer names as keys and Layer objects as values:

{
    "<someName1>": layer1,
    "<someName2>": layer2
}

The layer names can contain HTML, which allows you to add additional styling to the items:

{"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer}

Layers can be grouped using the option groupBy, for example layer names of the form "Group (label)":

new LayersControl(baseLayers, overlays, {
	inline: true,
	groupBy(name) {
		const [, group, label] = /^([^<>()]+) \((.+)\)$/.exec(name) ?? [];
		return group ? {group: `${group}:`, label} : undefined;
	}
}).addTo(map);

Constructor

ConstructorDescription
new LayersControl(baseLayers?: Record<string, Layer>, overlays?: Record<string, Layer>, options?: LayersControlOptions)

Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation.

Options

OptionTypeDefaultDescription
collapsedbooleantrue

If true, the control will be collapsed into an icon and expanded on pointer hover, touch, or keyboard activation. Ignored if inline is true.

inlinebooleanfalse

If true, the control is laid out like the attribution control: it is always expanded (without toggle button) and all entries are placed next to each other, wrapping onto multiple lines if necessary.

groupBy(name: string, layer: Layer, overlay: boolean) => LayersControlGroup | undefined

A function to group the entries. For each entry, it returns the name of its group and its label within the group, or undefined for an ungrouped entry. Consecutive entries of the same group (base layers and overlays separately) are rendered within one maplair-control-layers-group container, starting with the group name in a maplair-control-layers-group-name element, and each entry shows only its label. Events like baselayerchange still carry the full name. When combined with sortLayers, the entries are sorted first and grouped afterwards.

titlestring

The title of the toggle button and the accessible label of the layers list, the translation of 'Layers' by default.

toggleContentstring|HTMLElement

The content of the toggle button of a collapsed control instead of the layers icon: HTML (e.g. an icon or a character) or an element. String content is rendered as HTML; do not pass untrusted input.

collapseDelaynumber0

Collapse delay in milliseconds. If greater than 0, the control will remain open longer, making it easier to scroll through long layer lists.

positionstring'topright'

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

autoZIndexbooleantrue

If true, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.

hideSingleBasebooleanfalse

If true, the base layers in the control will be hidden when there is only one.

sortLayersbooleanfalse

Whether to sort the layers. When false, layers will keep the order in which they were added to the control.

sortFunction(layerA: Layer, layerB: Layer, nameA: string, nameB: string) => number

A compare function that will be used for sorting the layers, when sortLayers is true. The function receives both the Layer instances and their names, as in sortFunction(layerA, layerB, nameA, nameB). By default, it sorts layers alphabetically by their name.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
addTo(map: MaplairMap)this

Adds the control to the given map.

addBaseLayer(layer: Layer, name: string)this

Adds a base layer (radio button entry) with the given name to the control.

addOverlay(layer: Layer, name: string)this

Adds an overlay (checkbox entry) with the given name to the control.

removeLayer(layer: Layer)this

Remove the given layer from the control.

getLayers()LayersControlEntry[]

Returns the entries of the control in the order they are displayed.

selectLayer(layer: Layer)this

Selects the given layer of the control like a click on its entry: a base layer replaces the current base layer, an overlay is added to the map. The events baselayerchange and overlayadd are fired as for a click, but without originalEvent. Has no effect if the control is not on a map or does not contain the layer.

expand()this

Expand the control container if collapsed.

collapse()this

Collapse the control container if expanded.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

LegendControl extends Control

Constructor

ConstructorDescription
new LegendControl(options?: LegendControlOptions)

Creates a legend control.

Options

OptionTypeDefaultDescription
positionstring'bottomright'

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

collapsedbooleanfalse

If true, the legend starts collapsed to its title, which toggles it.

featureCountbooleanfalse

If true, the number of features is shown per class and per classification.

barbooleanfalse

If true, the feature count of each classification is shown as a bar of the class symbols, each as wide as its share.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
addClassification(layer: FeatureGroup, classification: Classification)this

Shows the classes of classification in the legend while layer is on the map, with the feature count of the layers of layer (e.g. a GeoJSON layer styled with classification.style), kept up to date when layers are added and removed.

removeClassification(layer: FeatureGroup)this

Removes the classification of layer from the legend.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

MiniMapControl extends Control

An overview map in a corner of the map, showing the view of the map as a rectangle (or rotated rectangle on a rotated map) at a smaller zoom level. Dragging the overview map pans the map, clicking it centers the map there, and a button collapses it.

Inspired by the Leaflet-MiniMap plugin.

Usage example

// a layer of its own, a layer can only be on one map
const overviewLayer = new TileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png');
new MiniMapControl(overviewLayer).addTo(map);

Constructor

ConstructorDescription
new MiniMapControl(layer: Layer, options?: MiniMapControlOptions)

Creates an overview map control showing layer (which must not be on another map).

Options

OptionTypeDefaultDescription
positionstring'bottomright'

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

widthnumber150

The width of the overview map in pixels.

heightnumber150

The height of the overview map in pixels.

zoomOffsetnumber-5

The zoom level of the overview map relative to the map.

collapsedbooleanfalse

Whether the overview map is collapsed initially.

rectangleOptionsPathOptions{color: '#ff7800', weight: 1, fillOpacity: 0.2}

The style of the rectangle showing the view of the map.

mapOptionsMaplairMapOptions{}

Further options of the overview map.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
addTo(map: MaplairMap)this

Adds the control to the given map.

getMiniMap()MaplairMap

Returns the overview map.

toggle()this

Collapses or expands the overview map.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

ScaleControl extends Control

A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems.

Usage example

new ScaleControl().addTo(map);

Constructor

ConstructorDescription
new ScaleControl(options?: ScaleControlOptions)

Creates a scale control with the given options.

Options

OptionTypeDefaultDescription
positionstring'bottomleft'

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

maxWidthnumber100

Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500).

metricbooleantrue

Whether to show the metric scale line (m/km).

imperialbooleantrue

Whether to show the imperial scale line (mi/ft).

updateWhenIdlebooleanfalse

If true, the control is updated on moveend, otherwise it's always up-to-date (updated on move).

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

SearchControl extends Control

A control with a search field for places, showing the results in a list to select one with the pointer or the keyboard. The selected result is shown on the map with a marker. It searches with a geocoder, e.g. Nominatim of OpenStreetMap or any other service. Coordinates like 47.27, 11.4 or geo:47.27,11.4 are found without a service.

The public Nominatim service is free, but limited by its usage policy: it is for occasional searches of users, not for heavy use (an absolute maximum of one request per second for all users of an app), and forbids auto-complete. The Nominatim geocoder follows the technical requirements, but you are responsible for your use of the service, which you confirm with the acceptUsagePolicy option: for more traffic, use your own Nominatim server or a commercial provider.

Usage example

new SearchControl({
    geocoder: SearchControl.nominatim({acceptUsagePolicy: true})
}).addTo(map);

// Photon of Komoot, which allows auto-complete
new SearchControl({
    autoComplete: true,
    async geocoder(query, {signal}) {
        const response = await fetch(`https://photon.komoot.io/api/?q=${encodeURIComponent(query)}`, {signal});
        const {features} = await response.json();
        return features.map(({geometry, properties}) => ({
            label: [properties.name, properties.city, properties.country].filter(Boolean).join(', '),
            latlng: [geometry.coordinates[1], geometry.coordinates[0]],
            raw: properties
        }));
    }
}).addTo(map);

Constructor

ConstructorDescription
new SearchControl(options?: SearchControlOptions)

Creates a search control.

Options

OptionTypeDefaultDescription
positionstring'topleft'

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

geocoderGeocoder

The function searching places (required), e.g. Nominatim. Coordinates (see LatLng.parse()) are found without it.

collapsedbooleantrue

If true, the control is collapsed into a button and expanded on click.

autoCompletebooleanfalse

Whether to search while typing instead of on Enter. Not with the public Nominatim service, its usage policy forbids auto-complete.

autoCompleteDelaynumber250

The delay in milliseconds after typing before searching with autoComplete.

minLengthnumber3

The minimum length of queries searched with autoComplete.

zoomnumber16

The zoom level for results without bounds, and the maximum zoom level for fitting the bounds of results.

markerboolean|((result: SearchResult) => Layer|null|undefined)true

Whether to show a marker at the selected result, or a function returning the layer to show instead, e.g. a CircleMarker highlighting the result (or nothing for none). The layer is removed when the search is cleared or another result is selected.

clearOnMapClickbooleanfalse

If true, a click on the map clears the search (the field, the results and the marker) and collapses the control. By default, the click only hides the results and the marker stays.

placeholderstring

The placeholder of the search field, by default the translation of "Search".

noResultsTextstring

The message shown if nothing is found, by default the translation of "No results".

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
expand()this

Expands the search field of a collapsed control and focuses it.

collapse()this

Collapses the control into its button, if collapsed, and hides the results.

select(result: SearchResult)this

Shows the given result on the map: zooms to it, shows a marker and fires searchresult on the map.

clear()this

Clears the search field, the results and the marker.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Static members

MethodReturnsDescription
nominatim({ url, params, acceptUsagePolicy }?: { url?: string | undefined; params?: Record<string, string> | undefined; acceptUsagePolicy?: boolean | undefined; })Geocoder

Returns a geocoder searching with Nominatim, by default the public service of OpenStreetMap. Using it requires that you read and accept its usage policy with the acceptUsagePolicy option, otherwise this throws an error. The geocoder sends at most one request per second, caches the results of the last 100 queries, adds the OpenStreetMap attribution to the map and does not search while typing with the public service. For more traffic, use your own Nominatim server or a commercial provider.

new SearchControl({
    geocoder: SearchControl.nominatim({acceptUsagePolicy: true, params: {countrycodes: 'at,de'}})
}).addTo(map);
layers(group: LayerGroup, { property, label, limit }?: { property?: string | undefined; label?: ((layer: Layer) => string | number | null | undefined) | undefined; limit?: number | undefined; })Geocoder

Returns a geocoder searching the layers of a layer group, e.g. the markers of a FeatureGroup or the features of a GeoJSON layer, by their label: a property of their GeoJSON feature (layer.feature.properties) or the result of a function. The group is searched at the time of the search, so layers added later are found as well, and nested groups without a label are searched recursively. The search ignores the case and finds the query anywhere in the label; labels starting with it come first, then in alphabetical order. The results contain the found layer and its GeoJSON feature as raw; layers without a single position (e.g. polygons) have the bounds and their center as latlng. Combine it with autoComplete to search while typing, and with marker false or a function to not cover the found marker with another one.

group
The layer group to search.
const stations = new GeoJSON(data, {
    onEachFeature: (feature, layer) => layer.bindTooltip(feature.properties.name)
}).addTo(map);
new SearchControl({
    geocoder: SearchControl.layers(stations, {property: 'name'}),
    autoComplete: true,
    minLength: 1,
    marker: false
}).addTo(map);
map.on('searchresult', ({result}) => result.layer.openTooltip());

SideBySideControl extends Control

Compares layers side by side: a vertical divider across the map shows the "left" layers on its left and the "right" layers on its right side. The divider can be dragged, or moved with the arrow keys. Works with layers having a container or element of their own, e.g. tile layers and image overlays.

Inspired by the leaflet-side-by-side plugin.

Usage example

const before = new TileLayer('https://…/2020/{z}/{x}/{y}.png').addTo(map);
const after = new TileLayer('https://…/2025/{z}/{x}/{y}.png').addTo(map);
new SideBySideControl(before, after).addTo(map);

Constructor

ConstructorDescription
new SideBySideControl(leftLayers?: Layer | Layer[], rightLayers?: Layer | Layer[], options?: SideBySideControlOptions)

Creates a side-by-side control for the given layers (which have to be added to the map separately).

Options

OptionTypeDefaultDescription
rationumber0.5

The initial position of the divider, from 0 (left) to 1 (right).

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
addTo(map: MaplairMap)this

Adds the control to the given map. The divider spans the map instead of being in a corner.

setLeftLayers(layers: Layer | Layer[])this

Sets the layers shown on the left side of the divider.

setRightLayers(layers: Layer | Layer[])this

Sets the layers shown on the right side of the divider.

getRatio()number

Returns the position of the divider, from 0 (left) to 1 (right).

setRatio(ratio: number)this

Moves the divider, from 0 (left) to 1 (right).

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

FullscreenControl extends Control

A control with a button to view the map in fullscreen and to exit it again. It is put on the map if you set its fullscreenControl option to true. Where the browser does not support the Fullscreen API (e.g. Safari on iPhone) or refuses fullscreen (e.g. in an iframe without allow="fullscreen"), the map is enlarged to the size of the window instead.

Usage example

new FullscreenControl({position: 'topright'}).addTo(map);

Constructor

ConstructorDescription
new FullscreenControl(options?: FullscreenControlOptions)

Creates a fullscreen control.

Options

OptionTypeDefaultDescription
positionstring'topleft'

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

enterTextstring

The HTML content of the button while the map is not in fullscreen, by default an expand icon.

exitTextstring

The HTML content of the button while the map is in fullscreen, by default a collapse icon.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

RotateControl extends Control

A compass showing the rotation of the map (see MaplairMap.setBearing()); clicking it rotates the map back to north up. It is put on the map if you set its rotateControl option to true.

Usage example

new RotateControl({position: 'topright'}).addTo(map);

Constructor

ConstructorDescription
new RotateControl(options?: RotateControlOptions)

Creates a rotate control.

Options

OptionTypeDefaultDescription
positionstring'topleft'

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

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

ButtonControl extends Control

A control with a button, styled like the zoom control, calling a function when clicked. It can have several states with their own content, title and function, e.g. to toggle something. Several buttons can be grouped with ButtonBarControl.

Inspired by the Leaflet.EasyButton plugin.

Usage example

new ButtonControl({
	content: '⌂',
	title: 'Home',
	onClick: (e, button, map) => map.setView([47.27, 11.40], 13)
}).addTo(map);

new ButtonControl({
	states: [{
		name: 'show',
		content: '👁',
		title: 'Show the markers',
		onClick(e, button, map) { markers.addTo(map); button.setState('hide'); }
	}, {
		name: 'hide',
		content: '🙈',
		title: 'Hide the markers',
		onClick(e, button) { markers.remove(); button.setState('show'); }
	}]
}).addTo(map);

Constructor

ConstructorDescription
new ButtonControl(options?: ButtonControlOptions)

Creates a button control.

Options

OptionTypeDefaultDescription
positionstring'topleft'

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

contentstring|HTMLElement''

The content of the button: HTML (e.g. an icon or a character) or an element. String content is rendered as HTML; do not pass untrusted input.

titlestring''

The title (tooltip) and accessible name of the button.

onClick(this: ButtonControl, e: MouseEvent, button: ButtonControl, map: MaplairMap) => void

Called with the click event, the ButtonControl and the map when clicking the button.

statesButtonControlState[]

Alternative states of the button, each an object with name and with content, title and onClick like the options. The first state is the initial one, setState() switches them.

classNamestring''

A custom CSS class name to assign to the button.

accessKeystring''

A key to activate the button with the browser's access key modifiers (e.g. Alt+Shift+K), shown in the title.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
setState(name: string)this

Switches to the state with the given name, see the states option.

getState()string | undefined

Returns the name of the current state, see the states option.

disable()this

Disables the button, so that clicking it does nothing.

enable()this

Enables the button again.

getButton()HTMLElement

Returns the button element.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

ButtonBarControl extends Control

Groups several ButtonControls in one bar, like the buttons of the zoom control.

Inspired by the Leaflet.EasyButton plugin.

Usage example

new ButtonBarControl([
	new ButtonControl({content: 'A', title: 'First', onClick: () => {}}),
	new ButtonControl({content: 'B', title: 'Second', onClick: () => {}})
]).addTo(map);

Constructor

ConstructorDescription
new ButtonBarControl(buttons: ButtonControl[], options?: ControlOptions)

Creates a bar with the given buttons.

Methods

MethodReturnsDescription
getButtons()ButtonControl[]

Returns the buttons of the bar.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

TextControl extends Control

A control showing a text or any content in a box, e.g. a title, a note on the data or a status. It is hidden while its content is empty.

Usage example

const status = new TextControl({position: 'topright', content: 'Loading…'}).addTo(map);
status.setContent(`Updated at ${new Date().toLocaleTimeString()}`);

Constructor

ConstructorDescription
new TextControl(options?: TextControlOptions)

Creates a text control.

Options

OptionTypeDefaultDescription
positionstring'topright'

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

contentstring|HTMLElement''

The content of the control: HTML or an element. String content is rendered as HTML; do not pass untrusted input.

classNamestring''

A custom CSS class name to assign to the control.

Options inherited from Control
OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
setContent(content: string | HTMLElement)this

Changes the content of the control.

getContent()string | HTMLElement

Returns the content of the control.

Methods inherited from Control
MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

ContextMenu extends Class

A menu opened with the contextmenu event (right click, or long tap on touch screens) on the map or on a layer. Each item calls a function with the location of the event. The menu is a popover, closed by clicking outside of it or pressing Escape, and can be used with the keyboard (arrow keys, Enter).

Inspired by the Leaflet.contextmenu plugin.

Usage example

new ContextMenu([
	{text: 'Center the map here', callback: e => map.panTo(e.latlng)},
	'-',
	{text: 'Zoom in', callback: () => map.zoomIn()}
]).addTo(map);

new ContextMenu([
	{text: 'Remove', callback: e => e.relatedTarget.remove()}
]).addTo(marker);

Constructor

ConstructorDescription
new ContextMenu(items: (ContextMenuItem | "-")[], options?: ContextMenuOptions)

Creates a context menu. Each item is an object with text, callback and the optional disabled, or '-' for a separator. The callback gets an event with latlng, containerPoint, layerPoint, originalEvent and relatedTarget (the layer, for menus of layers).

Options

OptionTypeDefaultDescription
classNamestring''

A custom CSS class name to assign to the menu.

Methods

MethodReturnsDescription
addTo(target: MaplairMap | Layer)this

Opens the menu on contextmenu events of the map or the layer.

remove()this

Removes the menu from its map or layer.

close()this

Closes the menu.

isOpen()boolean

Returns true if the menu is open.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

DragHandler extends Handler

Makes the map draggable (with panning inertia), enabled by default, see the map option dragging.

Constructor

ConstructorDescription
new DragHandler(map: MaplairMap)

Methods

MethodReturnsDescription
moved()boolean

Returns true if the map has been moved by the current or last drag.

moving()boolean

Returns true while the map is being dragged.

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

BoxZoomHandler extends Handler

Adds shift-drag zoom interaction to the map (zoom to a selected bounding box), enabled by default, see the map option boxZoom.

Methods

MethodReturnsDescription
moved()boolean

Returns true if a box has been drawn by the current or last interaction.

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

DoubleClickZoomHandler extends Handler

Handles double-click zoom on the map, enabled by default, see the map option doubleClickZoom.

Constructor

ConstructorDescription
new DoubleClickZoomHandler(map: MaplairMap)

Methods

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

ScrollWheelZoomHandler extends Handler

Enables mouse scroll wheel zoom on the map, as well as touchpad gestures: pinching zooms, and with scrollWheelZoom: 'trackpad' scrolling with two fingers pans. Enabled by default, see the map option scrollWheelZoom.

Constructor

ConstructorDescription
new ScrollWheelZoomHandler(map: MaplairMap)

Methods

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

KeyboardHandler extends Handler

Handles keyboard interaction with the map, enabled by default, see the map option keyboard. The ? key shows a list of the keyboard shortcuts.

Methods

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Static members

PropertyTypeDescription
keysRecord<"left" | "right" | "down" | "up" | "zoomIn" | "zoomOut", string[]>

The values of the keys for panning and zooming the map, so zoom keys follow the keyboard layout and cover the numpad too; = and _ keep the US + and - keys working both with and without Shift.

PinchZoomHandler extends Handler

Adds pinch zoom to the map on supported mobile browsers, enabled by default, see the map option pinchZoom.

Constructor

ConstructorDescription
new PinchZoomHandler(map: MaplairMap)

Methods

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

TapDragZoomHandler extends Handler

Zooms the map with one finger on touch devices: tap once, then touch again and drag down to zoom in or up to zoom out (as known from MapLibre GL JS and Google Maps). Enabled by default, see the map option tapDragZoom.

Constructor

ConstructorDescription
new TapDragZoomHandler(map: MaplairMap)

Methods

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

TapHoldHandler extends Handler

Simulates the contextmenu event on long hold, which otherwise is not fired by mobile Safari, see the map option tapHold.

Constructor

ConstructorDescription
new TapHoldHandler(map: MaplairMap)

Methods

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

DisplaceHandler extends Handler

Cartographic displacement of overlapping CircleMarkers: keeps all circle markers created with displace: true free of overlap.

Overlap is a screen space phenomenon: whether two markers cover each other depends on their pixel radius and the current zoom level. The displacement is therefore computed in projected pixel space and recomputed on every zoom. The true position of each marker is kept by the handler, the displaced position is applied via setLatLng. Since every run starts over from the true position, markers never drift.

maxDistance bounds how far a marker may be moved away from the truth, in meters. It is worth noting what such a limit costs at low zoom levels: if a marker is 11 km wide on the ground, separating two coincident ones moves each of them by some 6 km, so a limit below that leaves them overlapping.

Unlike the default handlers, it isn't added to every map, so that bundlers can drop it from applications that don't use it. Add it to the map class (or to a single map with DisplaceHandler.addTo(map, 'displace')), then enable it with the map option displace, which is either true or an object overriding the handler's options. It can be toggled at runtime via map.displace.enable() / map.displace.disable(); disabling restores the true positions.

Usage example

import { CircleMarker, DisplaceHandler, MaplairMap } from 'maplair';

MaplairMap.addInitHook('addHandler', 'displace', DisplaceHandler);

const map = new MaplairMap('map', {displace: { maxDistance: 10_000} });
new CircleMarker(latlng, { displace: true, radius: 6 }).addTo(map);

Constructor

ConstructorDescription
new DisplaceHandler(map: MaplairMap)

Options

OptionTypeDefaultDescription
gapnumber2

Additional pixel distance between the outlines of two markers.

iterationsnumber80

Maximum number of relaxation passes per relayout.

maxDistancenumberInfinity

Maximum distance in meters a marker may be moved away from its true position. Markers which would have to move further stay overlapping. Meters rather than pixels, since the point of the limit is to bound the geographic error. A limit in meters also scales itself: it only bites at the zoom levels where a pixel is worth a lot of ground.

Methods

MethodReturnsDescription
schedule()void

Requests a relayout in the next animation frame, at most one per frame.

relayout()void

Computes the displacement for all tracked markers in the pixel space of the current zoom level and writes the displaced positions back.

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

MarkerDrag extends Handler

The handler of Marker which makes the markers draggable, see the dragging property of markers and its draggable option.

Constructor

ConstructorDescription
new MarkerDrag(marker: Marker)

Creates the dragging handler of the given marker.

Methods

MethodReturnsDescription
moved()boolean

Returns true if the marker has been moved by the current or last drag.

Methods inherited from Handler
MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Util

Functions

MethodReturnsDescription
stamp(obj: object)number

Returns the unique ID of an object, assigning it one if it doesn't have it.

throttle(fn: (...args: any[]) => void, time: number, context?: object)(...args: any[]) => void

Returns a function which executes function fn with the given scope context (so that the this keyword refers to context inside fn's code). The function fn will be called no more than one time per given amount of time. The arguments received by the bound function will be any arguments passed when binding the function, followed by any arguments passed when invoking the bound function.

time
In milliseconds.
wrapNum(x: number, range: [number, number], includeMax?: boolean)number

Returns the number x modulo range in such a way so it lies within range[0] and range[1]. The returned value will always be smaller than range[1] unless includeMax is set to true.

falseFn()false

A function which always returns false.

formatNum(num: number, precision?: number | false)number

Returns the number num rounded with specified precision. The default precision value is 6 decimal places. false can be passed to skip any processing (can be useful to avoid round-off errors).

toNumber(value: unknown)number

Returns value if it's a number (including Infinity), converts it if it's a numeric string, and returns NaN for anything else, unlike Number(), which turns '', null and booleans into 0 or 1.

splitWords(str: string)string[]

Trims and splits the string on whitespace and returns the array of parts.

setOptions(obj: object, options?: object)object

Merges the given properties to the options of the obj object, returning the resulting options. See Class options.

template(str: string, data: Record<string, any>)string

Simple templating facility, accepts a template string of the form 'Hello {a}, {b}' and a data object like {a: 'foo', b: 'bar'}, returns evaluated string ('Hello foo, bar'). You can also specify functions instead of strings for data values — they will be evaluated passing data as an argument.

Properties

PropertyTypeDescription
lastIdnumber

Last unique ID used by stamp().

Transformation

Represents an affine transformation: a set of coefficients a, b, c, d for transforming a point of a form (x, y) into (a*x + b, c*y + d) and doing the reverse. Used by Maplair in its projections code.

Usage example

const transformation = new Transformation(2, 5, -1, 10),
	p = new Point(1, 2),
	p2 = transformation.transform(p), //  new Point(7, 8)
	p3 = transformation.untransform(p2); //  new Point(1, 2)

Constructor

ConstructorDescription
new Transformation(a: number | [number, number, number, number], b?: number, c?: number, d?: number)

Instantiates a Transformation object with the given coefficients. Alternatively, expects a coefficients array of the form [a, b, c, d].

Methods

MethodReturnsDescription
transform(point: Point, scale?: number)Point

Returns a transformed point, optionally multiplied by the given scale. Only accepts actual Point instances, not arrays.

untransform(point: Point, scale?: number)Point

Returns the reverse transformation of the given point, optionally divided by the given scale. Only accepts actual Point instances, not arrays.

LineUtil

Functions

MethodReturnsDescription
simplify(points: Point[], tolerance: number)Point[]

Dramatically reduces the number of points in a polyline while retaining its shape and returns a new array of simplified points, using the Ramer-Douglas-Peucker algorithm. Used for a huge performance boost when processing/displaying Maplair polylines for each zoom level and also reducing visual noise. tolerance affects the amount of simplification (lesser value means higher quality but slower and with more points). Also released as a separated micro-library Simplify.js.

pointToSegmentDistance(p: Point, p1: Point, p2: Point)number

Returns the distance between point p and segment p1 to p2.

closestPointOnSegment(p: Point, p1: Point, p2: Point)Point

Returns the closest point from a point p on a segment p1 to p2.

clipSegment(a: Point, b: Point, bounds: Bounds, useLastCode?: boolean, round?: boolean)[Point, Point] | false

Clips the segment a to b by rectangular bounds with the Cohen-Sutherland algorithm (modifying the segment points directly!). Used by Maplair to only show polyline points that are on the screen or near, increasing performance. Returns false if the segment is outside of the bounds.

isFlat(latlngs: LatLngExpression[] | LatLngExpression[][])boolean

Returns true if latlngs is a flat array, false is nested.

polylineCenter(latlngs: LatLngExpression[] | LatLngExpression[][], crs: typeof CRS)LatLng

Returns the center (centroid) of the passed LatLngs (first ring) from a polyline.

PolyUtil

Functions

MethodReturnsDescription
clipPolygon(points: Point[], bounds: Bounds, round?: boolean)Point[]

Clips the polygon geometry defined by the given points by the given bounds (using the Sutherland-Hodgman algorithm). Used by Maplair to only show polygon points that are on the screen or near, increasing performance. Note that polygon points needs different algorithm for clipping than polyline, so there's a separate method for it.

polygonCenter(latlngs: LatLngExpression[] | LatLngExpression[][], crs: typeof CRS)LatLng

Returns the center (centroid) of the passed LatLngs (first ring) from a polygon.

centroid(coords: LatLngExpression[])LatLng

Returns the 'center of mass' of the passed LatLngs.

I18n

Utility functions to deal with translations.

Translations of Maplair's built-in strings are maintained on Transifex and published in the i18n directory of the package. Load one before creating the map, see the example.

Usage example

import {I18n} from 'maplair';
import de from 'maplair/i18n/de.json' with {type: 'json'};

I18n.registerLocale('de', de);
I18n.setLocale('de');

Static members

MethodReturnsDescription
registerLocale(locale: string, messages?: Record<string, string>)void

Define localized strings for a given locale, defined by locale.

setLocale(locale: string | null)void

Define or change the locale code to be used when translating strings. Note that changing the locale does not affect already instantiated objects.

getLocale()string | null

Returns the current locale code, that will be used when translating strings.

translate(string: string, data?: Record<string, any>)string

Actually try to translate the string, with optional variable passed in data.

DomEvent

Functions

MethodReturnsDescription
on(obj: EventTarget, types: string | Record<string, (ev: any) => void>, fn?: ((ev: any) => void) | object, context?: object)void

Adds a listener function (fn) to a particular DOM event type of the element obj. 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as third argument.

off(obj: EventTarget, types?: string | Record<string, (ev: any) => void>, fn?: ((ev: any) => void) | object, context?: object, …args: any[])void

Removes a previously added listener function. Note that if you passed a custom context to on, you must pass the same context to off in order to remove the listener. Alternatively, removes a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}; with types only, removes all previously added listeners of given types; with the element only, removes all previously added listeners from the given element.

stopPropagation(e: Event | { originalEvent: Event; })void

Stop the given event from propagation to parent elements. Used inside the listener functions:

DomEvent.on(div, 'click', DomEvent.stopPropagation);

Also accepts a Maplair event with an originalEvent.

disableScrollPropagation(el: HTMLElement)void

Adds stopPropagation to the element's 'wheel' events (plus browser variants).

disableClickPropagation(el: HTMLElement)void

Adds stopPropagation to the element's 'dblclick', 'contextmenu' and 'pointerdown' events (plus browser variants). For 'click' events, prevents the map from handling the click while still allowing the native DOM click event to propagate normally.

preventDefault(e: Event)void

Prevents the default action of the DOM Event e from happening (such as following a link in the href of the a element, or doing a POST request with page reload when a <form> is submitted). Use it inside listener functions.

stop(e: Event)void

Does stopPropagation and preventDefault at the same time.

getPointerPosition(e: MouseEvent | Touch, container?: HTMLElement)Point

Gets normalized pointer position from a DOM event relative to the container (border excluded) or to the whole page if not specified.

getWheelPxFactor()number

Gets the wheel pixel factor based on the devicePixelRatio.

getWheelDelta(e: WheelEvent)number

Gets normalized wheel delta from a wheel DOM event, in vertical pixels scrolled (negative if scrolling down). Events from pointing devices without precise scrolling are mapped to a best guess of 60 pixels.

DomUtil

Functions

MethodReturnsDescription
get(id: string | HTMLElement)HTMLElement | null

Returns an element given its DOM id, or returns the element itself if it was passed directly.

create(tagName: string, className?: string, container?: HTMLElement)HTMLElement

Creates an HTML element with tagName, sets its class to className, and optionally appends it to container element.

toFront(el: Element)void

Makes el the last child of its parent, so it renders in front of the other children.

toBack(el: Element)void

Makes el the first child of its parent, so it renders behind the other children.

setTransform(el: HTMLElement | SVGElement, offset?: Point, scale?: number)void

Resets the 3D CSS transform of el so it is translated by offset pixels and optionally scaled by scale. Does not have an effect if the browser doesn't support 3D CSS transforms.

setPosition(el: HTMLElement | SVGElement, point: Point, flat?: boolean)void

Sets the position of el to coordinates specified by point using a CSS translate (used by Maplair internally to position its layers). With flat, the translate is 2D, so el is painted into its parent's compositor layer instead of getting a layer of its own.

getPosition(el: HTMLElement | SVGElement)Point

Returns the coordinates of an element previously positioned with setPosition.

disableImageDrag()void

Prevents the user from generating dragstart DOM events, usually generated when the user drags an image.

enableImageDrag()void

Cancels the effects of a previous DomUtil.disableImageDrag.

getSizedParentNode(element: HTMLElement)HTMLElement

Finds the closest parent node which size (width and height) is not null.

getScale(element: HTMLElement){ x: number; y: number; boundingClientRect: DOMRect; }

Computes the CSS scale currently applied on the element. Returns an object with x and y members as horizontal and vertical scales respectively, and boundingClientRect as the result of getBoundingClientRect().

Draggable extends Evented

A class for making DOM elements draggable. Used internally for map and marker dragging. Works on any DOM element.

Usage example

const draggable = new Draggable(elementToDrag);
draggable.enable();

Constructor

ConstructorDescription
new Draggable(element: HTMLElement, dragStartTarget?: HTMLElement, options?: DraggableOptions)

Creates a Draggable object for moving element when you start dragging the dragStartTarget element (equals element itself by default).

Options

OptionTypeDefaultDescription
clickTolerancenumber3

The max number of pixels a user can shift the pointer during a click for it to be considered a valid click (as opposed to a pointer drag).

Events

EventDataDescription
downMaplairEventFired when a drag is about to start.
dragstartDraggableEventFired when a drag starts.
predragDraggableEventFired continuously during dragging before each corresponding update of the element's position.
dragDraggableEventFired continuously during dragging.
dragendDragEndEventFired when the drag ends (with noInertia: true if the drag was finished without inertia, e.g. by disabling the draggable).

Methods

MethodReturnsDescription
enable()void

Enables the dragging ability.

disable()void

Disables the dragging ability.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Class

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

It implements a simple classical inheritance model using JavaScript's standard extends keyword, and introduces several special properties for convenient code organization — options and init hooks.

Options

options is a special property whose defaults, the static defaultOptions of the class, are merged with those of the parent class instead of overriding them completely, which makes managing configuration of objects and default values convenient:

class MyClass extends Class {
    static defaultOptions = {
        myOption1: 'foo',
        myOption2: 'bar'
    };
}

class MyChildClass extends MyClass {
    static defaultOptions = {
        myOption1: 'baz',
        myOption3: 5
    };
}

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

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

class MyClass extends Class {
    static defaultOptions = {
        foo: 'bar',
        bla: 5
    };

    constructor(options) {
        super();
        Util.setOptions(this, options);
        ...
    }
}

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

Note that the options object allows any keys, not just the options defined by the class and its base classes. This means you can use the options object to store application specific information, as long as you avoid keys that are already used by the class in question.

Mixins

You can add methods and properties from other objects using the include method (such objects are called mixins):

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

class MyClass extends Class {}

MyClass.include(MyMixin);

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

Constructor hooks

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

Polyline.addInitHook(function () {
    // ... do something in constructor additionally
    // e.g. add event listeners, set custom properties etc.
    this.editing = new PolylineEditor(this);
});

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

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

The hooks of a class run at the end of its constructor, which calls callInitHooks — so they can rely on everything the constructor sets up. All Maplair classes do so. Hooks of parent classes run first, and parent classes without a constructor of their own (such as Layer or Path) have their hooks run along with their subclasses. Each hook runs once per object.

Note that the hooks of a parent class run before the constructor of a subclass continues. To support hooks on your own classes, call this.callInitHooks() at the end of their constructor:

class MyMarker extends Marker {
    constructor(latlng, options) {
        super(latlng, options); // runs the hooks of Marker (and of Layer etc.)
        this.extra = 'ready';
        this.callInitHooks();   // runs the hooks of MyMarker
    }
}

Usage example

class MyClass extends Class {
    constructor(greeter) {
        super();
        this.greeter = greeter;
        this.callInitHooks(MyClass); // optional, see constructor hooks above
    }

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

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

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

Methods

MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Static members

MethodReturnsDescription
include(props: object)T

Includes a mixin into the current class: copies the properties of props (and of its prototypes) to the prototype of the class, and merges props.options into its default options.

mergeOptions(options: object)T

Merges options into the defaultOptions of the class.

setDefaultOptions(options: object)T

Use static defaultOptions = {…} or mergeOptions().

Deprecated alias of mergeOptions(), kept for code written for Maplair 4.0.

addInitHook(fn: ((this: any) => void) | string, …args: any[])T

Adds a constructor hook to the class: a function (called with the object as this), or the name of a method to call with the given arguments.

args
Arguments of the method fn.

Evented extends Class

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).

Usage example

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

Maplair 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(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Layer extends Evented

The base class of all Maplair layers, with the methods they share.

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

  • onAdd(map: MaplairMap): this should 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: MaplairMap): this should 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(): Object (optional) should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.
  • getAttribution(): String (optional) should return a string containing HTML to be shown on the Attribution control whenever the layer is visible.
  • getLegend(): HTMLElement|String (optional) should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.
  • beforeAdd(map: MaplairMap): this (optional) is 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.

Usage example

const layer = new 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 (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

Popup methods

MethodReturnsDescription
bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

Tooltip methods

MethodReturnsDescription
bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Other methods

MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

onAdd(map: MaplairMap)void

Should 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: MaplairMap)void

Should 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()Record<string, Function>

Should return an object like { viewreset: this._reset } for on. The event handlers in this object will be automatically added and removed from the map with your layer.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Properties

PropertyTypeDescription
featureFeature

The GeoJSON feature the layer was created from (by GeoJSON).

InteractiveLayerOptions extends LayerOptions

Options of interactive layers. Some layers can be made interactive - when the user interacts with such a layer, pointer events like click and pointerover can be handled. Use the event handling methods to handle these events.

Properties

OptionTypeDefaultDescription
interactivebooleantrue

If false, the layer will not emit pointer events and will act as a part of the underlying map.

bubblingPointerEventsbooleantrue

When true, a pointer event on this layer will trigger the same event on the map (unless DomEvent.stopPropagation is used).

Properties inherited from LayerOptions
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Control extends Class

Base class for map controls such as ZoomControl, AttributionControl, LayersControl and ScaleControl, which handles positioning them. Extend it to create your own controls.

Every control should extend from Control and (re-)implement the following methods:

  • onAdd(map: MaplairMap): HTMLElement should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).
  • onRemove(map: MaplairMap) (optional) should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().
  • getEvents(): Object (optional) should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Constructor

ConstructorDescription
new Control(options?: ControlOptions)

Options

OptionTypeDefaultDescription
positionstring'topright'

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

ordernumber0

The position of the control within its corner: controls with a lower order are closer to the corner of the map, those with the same order in the order of adding.

Methods

MethodReturnsDescription
getPosition()string

Returns the position of the control.

setPosition(position: string)this

Sets the position of the control.

getContainer()HTMLElement

Returns the HTMLElement that contains the control.

addTo(map: MaplairMap)this

Adds the control to the given map.

remove()this

Removes the control from the map it is currently active on.

onAdd(map: MaplairMap)HTMLElement

Should return the container DOM element for the control and add listeners on relevant map events. Called on control.addTo(map).

onRemove(map: MaplairMap)void

Should contain all clean up code that removes the listeners previously added in onAdd. Called on control.remove().

getEvents()Record<string, Function>

Should return an object like {zoomend: this._update} for on. The event handlers in this object will be automatically added and removed from the map with your control.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Handler extends Class

Abstract class for map interaction handlers, the base class of the handlers that are used internally to inject interaction features like dragging to classes like MaplairMap and Marker.

Classes inheriting from Handler implement the two following extension methods:

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

Constructor

ConstructorDescription
new Handler(map: MaplairMap)
map
The map the handler belongs to.

Methods

MethodReturnsDescription
enable()this

Enables the handler.

disable()this

Disables the handler.

enabled()boolean

Returns true if the handler is enabled.

addHooks()void

Called when the handler is enabled, should add event hooks.

removeHooks()void

Called when the handler is disabled, should remove the event hooks added previously.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Static members

MethodReturnsDescription
addTo(map: MaplairMap, name: string)T

Adds a new handler of this class to the given map with the given name, which is then available as the property of the map with this name.

Projection

BlanketOverlay extends Layer

Represents an HTML element that covers ("blankets") the entire surface of the map.

Do not use this class directly. It's meant for Renderer, and for plugins that rely on one single HTML element.

Subclasses must define the following methods:

  • _initContainer() must initialize the HTML element to use as blanket, and store it as this._container. The base implementation creates a blank <div>.
  • _destroyContainer() must destroy the HTML element in this._container and free any other resources. The base implementation destroys the element and removes any event handlers attached to it.
  • _resizeContainer(): Point: the base implementation resizes the container (based on the map's size and taking into account the padding), returning the new size in CSS pixels. Subclass implementations shall reset container parameters and data structures as needed.
  • _onZoomEnd(ev?: PointerEvent) (optional) runs on the map's zoomend event.
  • _onViewReset(ev?: PointerEvent) (optional) runs on the map's viewreset event.
  • _onSettled() runs whenever the map state settles after changing (at the end of pan/zoom animations, etc). This should trigger the bulk of any rendering logic. If the continuous option is set to true, then this also runs on any map state change (including during pan/zoom animations).

Constructor

ConstructorDescription
new BlanketOverlay(options?: BlanketOverlayOptions)

Options

OptionTypeDefaultDescription
paddingnumber0.1

How 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.

continuousbooleanfalse

When false, the blanket will update its position only when the map state settles (after a pan/zoom animation). When true, it will update when the map state changes (during pan/zoom animations).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
onAdd(map: MaplairMap)void
onRemove(map: MaplairMap)void
getEvents()Record<string, EventListener>

Returns the map events the blanket listens to.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

Renderer extends BlanketOverlay

Base class for vector renderer implementations (SVG, Canvas). Handles the DOM container of the renderer, its bounds, and its zoom animation.

A Renderer works as an implicit layer group for all 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 SVG and Canvas instead.

The continuous option inherited from BlanketOverlay cannot be set to true (otherwise, renderers get out of place during a pinch-zoom operation).

Constructor

ConstructorDescription
new Renderer(options?: RendererOptions)

Options

Options inherited from BlanketOverlay
OptionTypeDefaultDescription
paddingnumber0.1

How 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.

continuousbooleanfalse

When false, the blanket will update its position only when the map state settles (after a pan/zoom animation). When true, it will update when the map state changes (during pan/zoom animations).

Options inherited from Layer
OptionTypeDefaultDescription
panestring'overlayPane'

By default the layer will be added to the map's overlay pane (overlayPane). Overriding this option will cause the layer to be placed on another pane by default. Not effective if the renderer option is set (the renderer option will override the pane option).

attributionstring|nullnull

String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers.

attributionOrdernumber0

The position of the attribution in the attribution control: attributions are sorted by it, then by the order of adding, e.g. 1 keeps a legend last.

Events

EventDataDescription
updateMaplairEventFired when the renderer updates its bounds, center and zoom, for example when its map has moved.
Events inherited from Layer
EventDataDescription
addMaplairEventFired after the layer is added to a map.
removeMaplairEventFired after the layer is removed from a map.
clickMaplairPointerEventFired when the user clicks (or taps) the layer, if it is interactive.
dblclickMaplairPointerEventFired when the user double-clicks (or double-taps) the layer, if it is interactive.
pointerdownMaplairPointerEventFired when the user pushes the pointer on the layer, if it is interactive.
pointerupMaplairPointerEventFired when the user releases the pointer pushed on the layer, if it is interactive.
pointeroverMaplairPointerEventFired when the pointer enters the layer, if it is interactive.
pointeroutMaplairPointerEventFired when the pointer leaves the layer, if it is interactive.
contextmenuMaplairPointerEventFired when the user right-clicks on the layer, if it is interactive; 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).
popupopenPopupEventFired when a popup bound to this layer is opened.
popupclosePopupEventFired when a popup bound to this layer is closed.
tooltipopenTooltipEventFired when a tooltip bound to this layer is opened.
tooltipcloseTooltipEventFired when a tooltip bound to this layer is closed.

Methods

MethodReturnsDescription
onRemove()void

Removes the container of the renderer from the map.

Methods inherited from BlanketOverlay
MethodReturnsDescription
onAdd(map: MaplairMap)void
getEvents()Record<string, EventListener>

Returns the map events the blanket listens to.

Methods inherited from Layer
MethodReturnsDescription
addTo(map: MaplairMap | LayerGroup)this

Adds the layer to the given map or layer group.

remove()this

Removes the layer from the map it is currently active on.

removeFrom(obj: MaplairMap | LayerGroup)this

Removes the layer from the given map or LayerGroup.

getPane(name?: string)HTMLElement

Returns the HTMLElement representing the named pane on the map. If name is omitted, returns the pane for this layer.

setInteractive(interactive: boolean)this

Changes the interactive option of the layer, e.g. to stop a layer from emitting pointer events while it is being edited.

addInteractiveTarget(targetEl: HTMLElement)this

Registers targetEl, one of the layer's DOM elements, so that pointer, click and keyboard events on it (or its descendants) fire on the layer and bubble through its parent groups to the map, the way they do for markers and paths. Custom layers call it in onAdd, once the layer is on a map.

removeInteractiveTarget(targetEl: HTMLElement)this

Undoes addInteractiveTarget, typically in onRemove.

getAttribution()string | null

Used by the attribution control, returns the attribution option.

setAttribution(attribution: string | null)this

Changes the attribution option, also in the attribution control while the layer is on the map.

getLegend()HTMLElement|string

Should return an element (or a string containing HTML) to be shown on the LegendControl whenever the layer is visible. Fire legendchange on the layer when the legend changes.

beforeAdd(map: MaplairMap)void

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.

bindPopup(content: DivOverlayContent | Popup, options?: PopupOptions)this

Binds a popup to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindPopup()this

Removes the popup previously bound with bindPopup.

openPopup(latlng?: LatLngExpression)this

Opens the bound popup at the specified latlng or at the default popup anchor if no latlng is passed.

closePopup()this

Closes the popup bound to this layer if it is open.

togglePopup()this

Opens or closes the popup bound to this layer depending on its current state.

isPopupOpen()boolean

Returns true if the popup bound to this layer is currently open.

setPopupContent(content: DivOverlayContent)this

Sets the content of the popup bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getPopup()Popup | undefined

Returns the popup bound to this layer.

bindTooltip(content: DivOverlayContent | Tooltip, options?: TooltipOptions)this

Binds a tooltip to the layer with the passed content and sets up the necessary event listeners. A String argument is rendered as HTML; if it may contain untrusted input, sanitize it (e.g. with DOMPurify) or pass an HTMLElement with safe textContent instead. If a Function is passed it will receive the layer as the first argument and should return a String, HTMLElement or DocumentFragment.

unbindTooltip()this

Removes the tooltip previously bound with bindTooltip.

openTooltip(latlng?: LatLngExpression)this

Opens the bound tooltip at the specified latlng or at the default tooltip anchor if no latlng is passed.

closeTooltip()this

Closes the tooltip bound to this layer if it is open.

toggleTooltip()this

Opens or closes the tooltip bound to this layer depending on its current state.

isTooltipOpen()boolean

Returns true if the tooltip bound to this layer is currently open.

setTooltipContent(content: DivOverlayContent)this

Sets the content of the tooltip bound to this layer. String content is rendered as HTML; sanitize untrusted input or pass an HTMLElement with safe textContent instead.

getTooltip()Tooltip | undefined

Returns the tooltip bound to this layer.

Methods inherited from Evented
MethodReturnsDescription
on(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Adds 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'). Alternatively, adds a set of type/listener pairs, e.g. {click: onClick, pointermove: onPointerMove}, with the context as second argument.

off(types?: string | Record<string, EventListener>, fn?: EventListener | object, context?: object, …args: any[])this

Removes 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. Alternatively, removes a set of type/listener pairs. Without arguments, removes all listeners to all events on the object, including implicitly attached events.

fire(type: string, data?: object, propagate?: boolean)this

Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents.

listens(type: string, fn?: EventListener | boolean, context?: object, propagate?: boolean)boolean

Returns true if a particular event type has any listeners attached to it (or the given listener function, with the given context). The verification can optionally be propagated, it will return true if parents have the listener attached to it. Called as listens(type, propagate?) or listens(type, fn, context?, propagate?).

once(types: string | Record<string, EventListener>, fn?: EventListener | object, context?: object)this

Behaves as on(…), except the listener will only get fired once and then removed.

addEventParent(obj: Evented)this

Adds an event parent - an Evented that will receive propagated events.

removeEventParent(obj: Evented)this

Removes an event parent, so it will stop receiving propagated events.

Methods inherited from Class
MethodReturnsDescription
callInitHooks(cls?: Function)this

Runs the constructor hooks of the given class and of its parent classes, which haven't run yet for this object. Classes call it at the end of their constructor, e.g. this.callInitHooks(MyClass). Without cls, runs the hooks of all classes of this object.

CRS

Object that defines coordinate reference systems for projecting geographical points into pixel (screen) coordinates and back (and to coordinates in other units for WMS services). See spatial reference system.

Maplair defines the most usual CRSs by default. If you want to use a CRS not defined by default, extend CRS with a projection of your own, e.g. based on Proj4js (the Leaflet plugin Proj4Leaflet doesn't work with Maplair).

The CRSs are classes with static properties and methods only; they are not instantiated, the class itself is passed as the CRS, e.g. to the crs option of the map. Maplair's CRSs extend CRS (EarthCRS for the global ones).

Besides the properties and methods below, a CRS may define:

  • code: string: Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857').
  • wrapLng: [number, number]: An array of two numbers defining whether the longitude (horizontal) coordinate axis wraps around a given range and how. Defaults to [-180, 180] in most geographical CRSs. If undefined, the longitude axis does not wrap around.
  • wrapLat: [number, number]: Like wrapLng, but for the latitude (vertical) axis.
  • distance(latlng1: LatLng, latlng2: LatLng): number: Returns the distance between two geographical coordinates.

Static members

MethodReturnsDescription
latLngToPoint(latlng: LatLngExpression, zoom: number)Point

Projects geographical coordinates into pixel coordinates for a given zoom.

pointToLatLng(point: Point, zoom: number)LatLng

The inverse of latLngToPoint. Projects pixel coordinates on a given zoom into geographical coordinates.

project(latlng: LatLngExpression)Point

Projects geographical coordinates into coordinates in units accepted for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services).

unproject(point: Point)LatLng

Given a projected coordinate returns the corresponding LatLng. The inverse of project.

scale(zoom: number)number

Returns the scale used when transforming projected coordinates into pixel coordinates for a particular zoom. For example, it returns 256 * 2^zoom for Mercator-based CRS.

zoom(scale: number)number

Inverse of scale(), returns the zoom level corresponding to a scale factor of scale.

getProjectedBounds(zoom: number)Bounds | null

Returns the projection's bounds scaled and transformed for the provided zoom (null if the CRS is infinite).

wrapLatLng(latlng: LatLngExpression)LatLng

Returns a LatLng where lat and lng has been wrapped according to the CRS's wrapLat and wrapLng properties, if they are outside the CRS's bounds.

wrapLatLngBounds(bounds: LatLngBoundsExpression)LatLngBounds

Returns a LatLngBounds with the same size as the given one, ensuring that its center is within the CRS's bounds.

PropertyTypeDescription
projectionProjection | undefined

The projection of the CRS.

transformationTransformation | undefined

The transformation of projected coordinates into pixel coordinates at zoom 0.

infiniteboolean

If true, the coordinate space will be unbounded (infinite in both axes).

EarthCRS extends CRS

Serves as the base for CRS that are global such that they cover the earth. Can only be used as the base for other CRS and cannot be used directly, since it does not have a code, projection or transformation. distance() returns meters.

Static members

MethodReturnsDescription
distance(latlng1: LatLng, latlng2: LatLng)number

Returns the distance in meters between two geographical points using the Haversine approximation.

PropertyTypeDescription
wrapLng[number, number]

The range around which the longitude axis wraps.

Rnumber

Mean Earth Radius in meters, as recommended for use by the International Union of Geodesy and Geophysics, see https://rosettacode.org/wiki/Haversine_formula

EPSG3857 extends EarthCRS

The most common CRS for online maps, used by almost all free and commercial tile providers. Uses Spherical Mercator projection. Set in by default in Map's crs option.

Static members

PropertyTypeDescription
codestring
projectionProjection
transformationTransformation

EPSG900913 extends EPSG3857

The same as EPSG3857, with its former unofficial code EPSG:900913.

EPSG3395 extends EarthCRS

Rarely used by some commercial tile providers. Uses Elliptical Mercator projection.

Static members

PropertyTypeDescription
codestring
projectionProjection
transformationTransformation

EPSG4326 extends EarthCRS

A common CRS among GIS enthusiasts. Uses simple Equirectangular projection.

Maplair complies with the TMS coordinate scheme for EPSG:4326. If you are using a TileLayer with this CRS, ensure that there are two 256x256 pixel tiles covering the whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90), or (-180,-90) for TileLayers with the tms option set.

Static members

PropertyTypeDescription
codestring
projectionProjection
transformationTransformation

SimpleCRS extends CRS

A simple CRS that maps longitude and latitude into x and y directly. May be used for maps of flat surfaces (e.g. game maps). Note that the y axis should still be inverted (going from bottom to top). distance() returns simple euclidean distance.

Static members

MethodReturnsDescription
distance(latlng1: LatLng, latlng2: LatLng)number

Returns the euclidean distance between two points.

PropertyTypeDescription
projectionProjection
transformationTransformation

MaplairEvent

The base event object, the argument of event listeners. All other event objects contain these properties too. Whenever a class inheriting from Evented fires an event, a listener function is called with an event object containing information about the event, which depends on the event type. For example:

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

Properties

PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

EventListener

A listener of events, called with the event object, which has more properties depending on the event type (see the event objects below).

type EventListener = (event: MaplairEvent & Record<string, any>) => void

MaplairPointerEvent extends MaplairEvent

The event object of pointer events (click, pointermove, …).

Properties

PropertyTypeDescription
latlngLatLng

The geographical point where the pointer event occurred.

layerPointPoint

Pixel coordinates of the point where the pointer event occurred relative to the map layer.

containerPointPoint

Pixel coordinates of the point where the pointer event occurred relative to the map container.

originalEventMouseEvent|PointerEvent

The original DOM MouseEvent or DOM PointerEvent that triggered this Maplair event.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

MaplairKeyboardEvent extends MaplairEvent

The event object of keyboard events.

Properties

PropertyTypeDescription
originalEventKeyboardEvent

The original DOM KeyboardEvent that triggered this Maplair event.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

LocationEvent extends MaplairEvent

The event object of locationfound.

Properties

PropertyTypeDescription
latlngLatLng

Detected geographical location of the user.

boundsLatLngBounds

Geographical bounds of the area user is located in (with respect to the accuracy of location).

accuracynumber

Accuracy of location in meters.

altitudenumber

Height of the position above the WGS84 ellipsoid in meters.

altitudeAccuracynumber

Accuracy of altitude in meters.

headingnumber

The direction of travel in degrees counting clockwise from true North.

speednumber

Current velocity in meters per second.

timestampnumber

The time when the position was acquired.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

MaplairErrorEvent extends MaplairEvent

The event object of errors, e.g. locationerror.

Properties

PropertyTypeDescription
messagestring

Error message.

codenumber

Error code (if applicable).

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

LayerEvent extends MaplairEvent

The event object of adding and removing layers.

Properties

PropertyTypeDescription
layerLayer

The layer that was added or removed.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

LayersControlEvent extends MaplairEvent

The event object of the layers control.

Properties

PropertyTypeDescription
layerLayer

The layer that was added or removed.

namestring

The name of the layer that was added or removed.

originalEventEvent

The DOM event of the click on the entry in the layers control, undefined if the layer was added or removed by code.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

SearchResultEvent extends MaplairEvent

The event object of searchresult.

Properties

PropertyTypeDescription
resultSearchResult

The selected result.

latlngLatLng

The position of the result.

boundsLatLngBounds|undefined

The extent of the result, if any.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

TileEvent extends MaplairEvent

The event object of tile events.

Properties

PropertyTypeDescription
tileHTMLElement

The tile element (image).

coordsPoint

Point object with the tile's x, y, and z (zoom level) coordinates.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

TileErrorEvent extends TileEvent

The event object of tileerror.

Properties

PropertyTypeDescription
errorany

Error passed to the tile's done() callback.

Properties inherited from TileEvent
PropertyTypeDescription
tileHTMLElement

The tile element (image).

coordsPoint

Point object with the tile's x, y, and z (zoom level) coordinates.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

ResizeEvent extends MaplairEvent

The event object of resize.

Properties

PropertyTypeDescription
oldSizePoint

The old size before resize event.

newSizePoint

The new size after the resize event.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

CrsChangeEvent extends MaplairEvent

The event object of crschange.

Properties

PropertyTypeDescription
oldCrsCRS

The CRS of the map before the change.

crsCRS

The new CRS of the map.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

GeoJSONEvent extends MaplairEvent

The event object of adding GeoJSON features.

Properties

PropertyTypeDescription
layerLayer

The layer for the GeoJSON feature that is being added to the map.

propertiesobject

GeoJSON properties of the feature.

geometryTypestring

GeoJSON geometry type of the feature.

idstring|number

GeoJSON ID of the feature (if present).

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

PopupEvent extends MaplairEvent

The event object of opening and closing popups.

Properties

PropertyTypeDescription
popupPopup

The popup that was opened or closed.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

TooltipEvent extends MaplairEvent

The event object of opening and closing tooltips.

Properties

PropertyTypeDescription
tooltipTooltip

The tooltip that was opened or closed.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

DragEndEvent extends MaplairEvent

The event object of dragend.

Properties

PropertyTypeDescription
distancenumber

The distance in pixels the draggable element was moved by.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

ZoomAnimEvent extends MaplairEvent

The event object of zoomanim.

Properties

PropertyTypeDescription
centerLatLng

The current center of the map.

zoomnumber

The current zoom level of the map.

noUpdateboolean

Whether layers should update their contents due to this event.

Properties inherited from MaplairEvent
PropertyTypeDescription
typestring

The event type (e.g. 'click').

targetany

The object that fired the event. For propagated events, the last object in the propagation chain that fired the event.

sourceTargetany

The object that originally fired the event. For non-propagated events, this will be the same as the target.

propagatedFromany

For propagated events, the last object that propagated the event to its event parent.

LatLngExpression

A geographical point: a LatLng, an array of the form [lat, lng] or [lat, lng, alt], or a plain object of the form {lat, lng} or {lat, lng, alt} (lon can be used in place of lng). Accepted by all Maplair methods which accept LatLng objects (unless noted otherwise). Plain arrays (number[]) are accepted for JavaScript, where array literals in variables are no tuples.

type LatLngExpression = LatLng | [number, number] | [number, number, number] | number[] | { lat: number; lng: number; alt?: number; } | { lat: number; lon: number; alt?: number; }

LatLngBoundsExpression

A geographical area: a LatLngBounds, or an array of geographical points (usually two diagonally opposite corners), e.g. [[40.712, -74.227], [40.774, -74.125]]. Accepted by all Maplair methods which accept LatLngBounds objects (unless noted otherwise).

type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]

PointExpression

A point in pixels: a Point, an array of the form [x, y], or a plain object of the form {x, y}. Accepted by all Maplair methods and options which accept Point objects (unless noted otherwise).

type PointExpression = Point | [number, number] | number[] | { x: number; y: number; }

BoundsExpression

A rectangular area in pixel coordinates: a Bounds, or an array of points (usually two diagonally opposite corners), e.g. [[10, 10], [40, 60]]. Accepted by all Maplair methods which accept Bounds objects (unless noted otherwise).

type BoundsExpression = Bounds | PointExpression[]

ZoomOptions

Options of the MaplairMap methods which modify the zoom level.

Properties

PropertyTypeDescription
animateboolean

If not specified, zoom animation will happen if the zoom origin is inside the current view, and if the user prefers reduced motion, only when zooming by at most one level. If true, the map will attempt animating zoom disregarding where zoom origin is and the user's reduced motion preference. Setting false will make it always reset the view completely without animation.

PanOptions

Options of the MaplairMap methods which modify the center of the map.

Properties

OptionTypeDefaultDescription
animateboolean

If true, panning will always be animated if possible, even if the user prefers reduced motion. 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). If not specified, panning is animated, except for pans longer than half the map size when the user prefers reduced motion.

durationnumber0.25

Duration of animated panning, in seconds.

easeLinearitynumber0.25

The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, and the smaller this number, the more bowed the curve.

noMoveStartbooleanfalse

If true, panning won't fire movestart event on start (used internally for panning inertia).

ZoomPanOptions extends ZoomOptions, PanOptions

Options of the MaplairMap methods which modify the zoom level and the center.

Properties

PropertyTypeDescription
animateboolean

Whether to animate the change: like ZoomOptions.animate if the zoom level changes, and like PanOptions.animate otherwise. The zoom and pan options can set it for each case separately.

resetboolean

If true, the view is reset without animation.

zoomZoomOptions

Options for the zoom part of the change, taking precedence over animate.

panPanOptions

Options for the pan part of the change, taking precedence over animate.

Properties inherited from ZoomOptions
PropertyTypeDescription
animateboolean

If not specified, zoom animation will happen if the zoom origin is inside the current view, and if the user prefers reduced motion, only when zooming by at most one level. If true, the map will attempt animating zoom disregarding where zoom origin is and the user's reduced motion preference. Setting false will make it always reset the view completely without animation.

Properties inherited from PanOptions
PropertyTypeDescription
animateboolean

If true, panning will always be animated if possible, even if the user prefers reduced motion. 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). If not specified, panning is animated, except for pans longer than half the map size when the user prefers reduced motion.

durationnumber

Duration of animated panning, in seconds.

easeLinearitynumber

The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, and the smaller this number, the more bowed the curve.

noMoveStartboolean

If true, panning won't fire movestart event on start (used internally for panning inertia).

FitBoundsOptions extends ZoomPanOptions, PaddingOptions

Options of MaplairMap.fitBounds() and similar methods.

Properties

OptionTypeDefaultDescription
maxZoomnumber|nullnull

The maximum possible zoom to use.

Properties inherited from ZoomPanOptions
OptionTypeDefaultDescription
animateboolean

Whether to animate the change: like ZoomOptions.animate if the zoom level changes, and like PanOptions.animate otherwise. The zoom and pan options can set it for each case separately.

resetboolean

If true, the view is reset without animation.

zoomZoomOptions

Options for the zoom part of the change, taking precedence over animate.

panPanOptions

Options for the pan part of the change, taking precedence over animate.

Properties inherited from PaddingOptions
OptionTypeDefaultDescription
paddingTopLeftPointExpression[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.

paddingBottomRightPointExpression[0, 0]

The same for the bottom right corner of the map.

paddingPointExpression[0, 0]

Equivalent of setting both top left and bottom right padding to the same value.

Properties inherited from ZoomOptions
OptionTypeDefaultDescription
animateboolean

If not specified, zoom animation will happen if the zoom origin is inside the current view, and if the user prefers reduced motion, only when zooming by at most one level. If true, the map will attempt animating zoom disregarding where zoom origin is and the user's reduced motion preference. Setting false will make it always reset the view completely without animation.

Properties inherited from PanOptions
OptionTypeDefaultDescription
animateboolean

If true, panning will always be animated if possible, even if the user prefers reduced motion. 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). If not specified, panning is animated, except for pans longer than half the map size when the user prefers reduced motion.

durationnumber0.25

Duration of animated panning, in seconds.

easeLinearitynumber0.25

The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, and the smaller this number, the more bowed the curve.

noMoveStartbooleanfalse

If true, panning won't fire movestart event on start (used internally for panning inertia).

InvalidateSizeOptions extends PanOptions

Options of MaplairMap.invalidateSize().

Properties

OptionTypeDefaultDescription
animatebooleanfalse

If true, the map pans to its new center with animation.

panbooleantrue

If false, panning will not occur.

debounceMoveendbooleanfalse

If true, it will delay moveend event so that it doesn't happen often even if the method is called many times in a row.

Properties inherited from PanOptions
OptionTypeDefaultDescription
animateboolean

If true, panning will always be animated if possible, even if the user prefers reduced motion. 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). If not specified, panning is animated, except for pans longer than half the map size when the user prefers reduced motion.

durationnumber0.25

Duration of animated panning, in seconds.

easeLinearitynumber0.25

The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). 1.0 means linear animation, and the smaller this number, the more bowed the curve.

noMoveStartbooleanfalse

If true, panning won't fire movestart event on start (used internally for panning inertia).

LocateOptions

Options of the geolocation methods of MaplairMap, e.g. locate().

Properties

OptionTypeDefaultDescription
watchbooleanfalse

If true, starts continuous watching of location changes (instead of detecting it once) using W3C watchPosition method. You can later stop watching using map.stopLocate() method.

setViewbooleanfalse

If true, automatically sets the map view to the user location with respect to detection accuracy, or to world view if geolocation failed.

maxZoomnumberInfinity

The maximum zoom for automatic view setting when using setView option.

timeoutnumber10000

Number of milliseconds to wait for a response from geolocation before firing a locationerror event.

maximumAgenumber0

Maximum age of detected location. If less than this amount of milliseconds passed since last geolocation response, locate will return a cached location.

enableHighAccuracybooleanfalse

Enables high accuracy, see description in the W3C spec.

PaddingOptions

Padding options of MaplairMap methods, e.g. panInside().

Properties

OptionTypeDefaultDescription
paddingTopLeftPointExpression[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.

paddingBottomRightPointExpression[0, 0]

The same for the bottom right corner of the map.

paddingPointExpression[0, 0]

Equivalent of setting both top left and bottom right padding to the same value.

SearchResult

A result of a search, returned by a geocoder.

Properties

PropertyTypeDescription
labelstring

The text shown in the list of results, e.g. an address.

latlngLatLngExpression

The position of the result.

boundsLatLngBoundsExpression

The extent of the result, e.g. of a city, which the map fits to instead of zooming to the position.

rawany

The original result of the service, for use in event listeners.

layerLayer

The found layer, by SearchControl.layers(), e.g. to open its tooltip in a searchresult listener.

Geocoder

A function searching places for a query, see the geocoder option. It should pass the signal to fetch(): searches are aborted when the user starts another one. Optional properties of the function: attribution, an attribution text which the control adds to the map, and autoComplete: false if the service forbids searching while typing (overriding the autoComplete option).

type Geocoder = ((query: string, options: { signal: AbortSignal; }) => Promise<SearchResult[]>) & { attribution?: string; autoComplete?: boolean; }

version

A constant that represents the Maplair version in use.

Properties

PropertyTypeDescription
versionstring

A constant that represents the Maplair version in use.