MapLibre GL JS
API Reference
On This Page
Table of Contents
- Map
- Parameters
- Examples
- scrollZoom
- boxZoom
- dragRotate
- dragPan
- keyboard
- doubleClickZoom
- touchZoomRotate
- touchPitch
- addControl
- removeControl
- hasControl
- resize
- getBounds
- getMaxBounds
- setMaxBounds
- setMinZoom
- getMinZoom
- setMaxZoom
- getMaxZoom
- setMinPitch
- getMinPitch
- setMaxPitch
- getMaxPitch
- getRenderWorldCopies
- setRenderWorldCopies
- project
- unproject
- isMoving
- isZooming
- isRotating
- on
- once
- once
- off
- off
- queryRenderedFeatures
- querySourceFeatures
- setStyle
- getStyle
- isStyleLoaded
- addSource
- isSourceLoaded
- areTilesLoaded
- removeSource
- getSource
- addImage
- updateImage
- hasImage
- removeImage
- loadImage
- listImages
- addLayer
- moveLayer
- removeLayer
- getLayer
- setLayerZoomRange
- setFilter
- getFilter
- setPaintProperty
- getPaintProperty
- setLayoutProperty
- getLayoutProperty
- setLight
- getLight
- setFeatureState
- removeFeatureState
- getFeatureState
- getContainer
- getCanvasContainer
- getCanvas
- loaded
- remove
- triggerRepaint
- showTileBoundaries
- showPadding
- showCollisionBoxes
- repaint
- version
- getCenter
- setCenter
- panBy
- panTo
- getZoom
- setZoom
- zoomTo
- zoomIn
- zoomOut
- getBearing
- setBearing
- getPadding
- setPadding
- rotateTo
- resetNorth
- resetNorthPitch
- snapToNorth
- getPitch
- setPitch
- cameraForBounds
- fitBounds
- fitScreenCoordinates
- jumpTo
- easeTo
- flyTo
- stop
- resize
- remove
- mousedown
- mouseup
- mouseover
- mousemove
- click
- dblclick
- mouseenter
- mouseleave
- mouseout
- contextmenu
- wheel
- touchstart
- touchend
- touchmove
- touchcancel
- movestart
- move
- moveend
- dragstart
- drag
- dragend
- zoomstart
- zoom
- zoomend
- rotatestart
- rotate
- rotateend
- pitchstart
- pitch
- pitchend
- boxzoomstart
- boxzoomend
- boxzoomcancel
- webglcontextlost
- webglcontextrestored
- load
- render
- idle
- error
- data
- styledata
- sourcedata
- dataloading
- styledataloading
- sourcedataloading
- styleimagemissing
Map
Extends Evented
The Map
object represents the map on your page. It exposes methods
and properties that enable you to programmatically change the map,
and fires events as users interact with it.
You create a Map
by specifying a container
and other options.
Then Mapbox GL JS initializes the map on the page and returns your Map
object.
Parameters
options
Objectoptions.container
(HTMLElement | string) The HTML element in which Mapbox GL JS will render the map, or the element’s stringid
. The specified element must have no children.options.minZoom
number The minimum zoom level of the map (0-24). (optional, default0
)options.maxZoom
number The maximum zoom level of the map (0-24). (optional, default22
)options.minPitch
number The minimum pitch of the map (0-60). (optional, default0
)options.maxPitch
number The maximum pitch of the map (0-60). (optional, default60
)options.style
(Object | string)? The map’s Mapbox style. This must be an a JSON object conforming to the schema described in the Mapbox Style Specification, or a URL to such JSON.To load a style from the Mapbox API, you can use a URL of the formmapbox://styles/:owner/:style
, where:owner
is your Mapbox account name and:style
is the style ID. Or you can use one of the following the predefined Mapbox styles:-mapbox://styles/mapbox/streets-v11
mapbox://styles/mapbox/outdoors-v11
mapbox://styles/mapbox/light-v10
mapbox://styles/mapbox/dark-v10
mapbox://styles/mapbox/satellite-v9
mapbox://styles/mapbox/satellite-streets-v11
mapbox://styles/mapbox/navigation-preview-day-v4
mapbox://styles/mapbox/navigation-preview-night-v4
mapbox://styles/mapbox/navigation-guidance-day-v4
mapbox://styles/mapbox/navigation-guidance-night-v4
Tilesets hosted with Mapbox can be style-optimized if you append?optimize=true
to the end of your style URL, likemapbox://styles/mapbox/streets-v11?optimize=true
. Learn more about style-optimized vector tiles in our API documentation.
options.hash
(boolean | string) Iftrue
, the map’s position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page’s URL. For example,http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60
. An additional string may optionally be provided to indicate a parameter-styled hash, e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo is a custom parameter and bar is an arbitrary hash distinct from the map hash. (optional, defaultfalse
)options.interactive
boolean Iffalse
, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction. (optional, defaulttrue
)options.bearingSnap
number The threshold, measured in degrees, that determines when the map’s bearing will snap to north. For example, with abearingSnap
of 7, if the user rotates the map within 7 degrees of north, the map will automatically snap to exact north. (optional, default7
)options.pitchWithRotate
boolean Iffalse
, the map’s pitch (tilt) control with “drag to rotate” interaction will be disabled. (optional, defaulttrue
)options.clickTolerance
number The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag). (optional, default3
)options.attributionControl
boolean Iftrue
, an AttributionControl will be added to the map. (optional, defaulttrue
)options.customAttribution
(string | Array<string>)? String or strings to show in an AttributionControl. Only applicable ifoptions.attributionControl
istrue
.options.logoPosition
string A string representing the position of the Mapbox wordmark on the map. Valid options aretop-left
,top-right
,bottom-left
,bottom-right
. (optional, default'bottom-left'
)options.failIfMajorPerformanceCaveat
boolean Iftrue
, map creation will fail if the performance of Mapbox GL JS would be dramatically worse than expected (i.e. a software renderer would be used). (optional, defaultfalse
)options.preserveDrawingBuffer
boolean Iftrue
, the map’s canvas can be exported to a PNG usingmap.getCanvas().toDataURL()
. This isfalse
by default as a performance optimization. (optional, defaultfalse
)options.antialias
boolean? Iftrue
, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this isfalse
by default as a performance optimization.options.refreshExpiredTiles
boolean Iffalse
, the map won’t attempt to re-request tiles once they expire per their HTTPcacheControl
/expires
headers. (optional, defaulttrue
)options.maxBounds
LngLatBoundsLike? If set, the map will be constrained to the given bounds.options.scrollZoom
(boolean | Object) Iftrue
, the “scroll to zoom” interaction is enabled. AnObject
value is passed as options to ScrollZoomHandler#enable. (optional, defaulttrue
)options.boxZoom
boolean Iftrue
, the “box zoom” interaction is enabled (see BoxZoomHandler). (optional, defaulttrue
)options.dragRotate
boolean Iftrue
, the “drag to rotate” interaction is enabled (see DragRotateHandler). (optional, defaulttrue
)options.dragPan
(boolean | Object) Iftrue
, the “drag to pan” interaction is enabled. AnObject
value is passed as options to DragPanHandler#enable. (optional, defaulttrue
)options.keyboard
boolean Iftrue
, keyboard shortcuts are enabled (see KeyboardHandler). (optional, defaulttrue
)options.doubleClickZoom
boolean Iftrue
, the “double click to zoom” interaction is enabled (see DoubleClickZoomHandler). (optional, defaulttrue
)options.touchZoomRotate
(boolean | Object) Iftrue
, the “pinch to rotate and zoom” interaction is enabled. AnObject
value is passed as options to TouchZoomRotateHandler#enable. (optional, defaulttrue
)options.touchPitch
(boolean | Object) Iftrue
, the “drag to pitch” interaction is enabled. AnObject
value is passed as options to TouchPitchHandler#enable. (optional, defaulttrue
)options.trackResize
boolean Iftrue
, the map will automatically resize when the browser window resizes. (optional, defaulttrue
)options.center
LngLatLike The inital geographical centerpoint of the map. Ifcenter
is not specified in the constructor options, Mapbox GL JS will look for it in the map’s style object. If it is not specified in the style, either, it will default to[0, 0]
Note: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON. (optional, default[0,0]
)options.zoom
number The initial zoom level of the map. Ifzoom
is not specified in the constructor options, Mapbox GL JS will look for it in the map’s style object. If it is not specified in the style, either, it will default to0
. (optional, default0
)options.bearing
number The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. Ifbearing
is not specified in the constructor options, Mapbox GL JS will look for it in the map’s style object. If it is not specified in the style, either, it will default to0
. (optional, default0
)options.pitch
number The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). Ifpitch
is not specified in the constructor options, Mapbox GL JS will look for it in the map’s style object. If it is not specified in the style, either, it will default to0
. (optional, default0
)options.bounds
LngLatBoundsLike? The initial bounds of the map. Ifbounds
is specified, it overridescenter
andzoom
constructor options.options.fitBoundsOptions
Object? A Map#fitBounds options object to use only when fitting the initialbounds
provided above.options.renderWorldCopies
boolean Iftrue
, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set tofalse
:- When the map is zoomed out far enough that a single representation of the world does not fill the map’s entire container, there will be blank space beyond 180 and -180 degrees longitude.- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
map and the other on the left edge of the map) at every zoom level. (optional, default
true
)
- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
map and the other on the left edge of the map) at every zoom level. (optional, default
options.maxTileCacheSize
number The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport. (optional, defaultnull
)options.localIdeographFontFamily
string Defines a CSS font-family for locally overriding generation of glyphs in the ‘CJK Unified Ideographs’, ‘Hiragana’, ‘Katakana’ and ‘Hangul Syllables’ ranges. In these ranges, font settings from the map’s style will be ignored, except for font-weight keywords (light/regular/medium/bold). Set tofalse
, to enable font settings from the map’s style for these glyph ranges. Note that Mapbox Studio sets this value tofalse
by default. The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See Use locally generated ideographs.) (optional, default'sans-serif'
)options.transformRequest
RequestTransformFunction A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. Expected to return an object with aurl
property and optionallyheaders
andcredentials
properties. (optional, defaultnull
)options.collectResourceTiming
boolean Iftrue
, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in aresourceTiming
property of relevantdata
events. (optional, defaultfalse
)options.fadeDuration
number Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading. (optional, default300
)options.crossSourceCollisions
boolean Iftrue
, symbols from multiple sources can collide with each other during collision detection. Iffalse
, collision detection is run separately for the symbols in each source. (optional, defaulttrue
)options.accessToken
string If specified, map will use this token instead of the one defined in mapboxgl.accessToken. (optional, defaultnull
)options.locale
Object A patch to apply to the default localization table for UI strings, e.g. control tooltips. Thelocale
object maps namespaced UI string IDs to translated strings in the target language; seesrc/ui/default_locale.js
for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table). (optional, defaultnull
)
Examples
var map = new mapboxgl.Map({
container: 'map',
center: [-122.420679, 37.772537],
zoom: 13,
style: style_object,
hash: true,
transformRequest: (url, resourceType)=> {
if(resourceType === 'Source' && url.startsWith('http://myHost')) {
return {
url: url.replace('http', 'https'),
headers: { 'my-custom-header': true},
credentials: 'include' // Include cookies for cross-origin requests
}
}
}
});
scrollZoom
The map’s ScrollZoomHandler, which implements zooming in and out with a scroll wheel or trackpad.
Find more details and examples using scrollZoom
in the ScrollZoomHandler section.
Type: ScrollZoomHandler
boxZoom
The map’s BoxZoomHandler, which implements zooming using a drag gesture with the Shift key pressed.
Find more details and examples using boxZoom
in the BoxZoomHandler section.
Type: BoxZoomHandler
dragRotate
The map’s DragRotateHandler, which implements rotating the map while dragging with the right
mouse button or with the Control key pressed. Find more details and examples using dragRotate
in the DragRotateHandler section.
Type: DragRotateHandler
dragPan
The map’s DragPanHandler, which implements dragging the map with a mouse or touch gesture.
Find more details and examples using dragPan
in the DragPanHandler section.
Type: DragPanHandler
keyboard
The map’s KeyboardHandler, which allows the user to zoom, rotate, and pan the map using keyboard
shortcuts. Find more details and examples using keyboard
in the KeyboardHandler section.
Type: KeyboardHandler
doubleClickZoom
The map’s DoubleClickZoomHandler, which allows the user to zoom by double clicking.
Find more details and examples using doubleClickZoom
in the DoubleClickZoomHandler section.
Type: DoubleClickZoomHandler
touchZoomRotate
The map’s TouchZoomRotateHandler, which allows the user to zoom or rotate the map with touch gestures.
Find more details and examples using touchZoomRotate
in the TouchZoomRotateHandler section.
Type: TouchZoomRotateHandler
touchPitch
The map’s TouchPitchHandler, which allows the user to pitch the map with touch gestures.
Find more details and examples using touchPitch
in the TouchPitchHandler section.
Type: TouchPitchHandler
addControl
Adds an IControl to the map, calling control.onAdd(this)
.
Parameters
control
IControl The IControl to add.position
string? position on the map to which the control will be added. Valid values are'top-left'
,'top-right'
,'bottom-left'
, and'bottom-right'
. Defaults to'top-right'
.
Examples
// Add zoom and rotation controls to the map.
map.addControl(new mapboxgl.NavigationControl());
Returns Map this
removeControl
Removes the control from the map.
Parameters
control
IControl The IControl to remove.
Examples
// Define a new navigation control.
var navigation = new mapboxgl.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Remove zoom and rotation controls from the map.
map.removeControl(navigation);
Returns Map this
hasControl
Checks if a control exists on the map.
Parameters
control
IControl The IControl to check.
Examples
// Define a new navigation control.
var navigation = new mapboxgl.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Check that the navigation control exists on the map.
map.hasControl(navigation);
Returns boolean True if map contains control.
resize
Resizes the map according to the dimensions of its
container
element.
Checks if the map container size changed and updates the map if it has changed.
This method must be called after the map’s container
is resized programmatically
or when the map is shown after being initially hidden with CSS.
Parameters
eventData
Object? Additional properties to be passed tomovestart
,move
,resize
, andmoveend
events that get triggered as a result of resize. This can be useful for differentiating the source of an event (for example, user-initiated or programmatically-triggered events).
Examples
// Resize the map when the map container is shown
// after being initially hidden with CSS.
var mapDiv = document.getElementById('map');
if (mapDiv.style.visibility === true) map.resize();
Returns Map this
getBounds
Returns the map’s geographical bounds. When the bearing or pitch is non-zero, the visible region is not an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
Examples
var bounds = map.getBounds();
Returns LngLatBounds The geographical bounds of the map as LngLatBounds.
getMaxBounds
Returns the maximum geographical bounds the map is constrained to, or null
if none set.
Examples
var maxBounds = map.getMaxBounds();
Returns **(LngLatBounds | null)** The map object. |
setMaxBounds
Sets or clears the map’s geographical bounds.
Pan and zoom operations are constrained within these bounds. If a pan or zoom is performed that would display regions outside these bounds, the map will instead display a position and zoom level as close as possible to the operation’s request while still remaining within the bounds.
Parameters
-
bounds
**(LngLatBoundsLikenull undefined)** The maximum bounds to set. If null
orundefined
is provided, the function removes the map’s maximum bounds.
Examples
// Define bounds that conform to the `LngLatBoundsLike` object.
var bounds = [
[-74.04728, 40.68392], // [west, south]
[-73.91058, 40.87764] // [east, north]
];
// Set the map's max bounds.
map.setMaxBounds(bounds);
Returns Map this
setMinZoom
Sets or clears the map’s minimum zoom level. If the map’s current zoom level is lower than the new minimum, the map will zoom to the new minimum.
It is not always possible to zoom out and reach the set minZoom
.
Other factors such as map height may restrict zooming. For example,
if the map is 512px tall it will not be possible to zoom below zoom 0
no matter what the minZoom
is set to.
Parameters
minZoom
(number | null | undefined) The minimum zoom level to set (-2 - 24). Ifnull
orundefined
is provided, the function removes the current minimum zoom (i.e. sets it to -2).
Examples
map.setMinZoom(12.25);
Returns Map this
getMinZoom
Returns the map’s minimum allowable zoom level.
Examples
var minZoom = map.getMinZoom();
Returns number minZoom
setMaxZoom
Sets or clears the map’s maximum zoom level. If the map’s current zoom level is higher than the new maximum, the map will zoom to the new maximum.
Parameters
maxZoom
(number | null | undefined) The maximum zoom level to set. Ifnull
orundefined
is provided, the function removes the current maximum zoom (sets it to 22).
Examples
map.setMaxZoom(18.75);
Returns Map this
getMaxZoom
Returns the map’s maximum allowable zoom level.
Examples
var maxZoom = map.getMaxZoom();
Returns number maxZoom
setMinPitch
Sets or clears the map’s minimum pitch. If the map’s current pitch is lower than the new minimum, the map will pitch to the new minimum.
Parameters
minPitch
(number | null | undefined) The minimum pitch to set (0-60). Ifnull
orundefined
is provided, the function removes the current minimum pitch (i.e. sets it to 0).
Returns Map this
getMinPitch
Returns the map’s minimum allowable pitch.
Returns number minPitch
setMaxPitch
Sets or clears the map’s maximum pitch. If the map’s current pitch is higher than the new maximum, the map will pitch to the new maximum.
Parameters
maxPitch
(number | null | undefined) The maximum pitch to set. Ifnull
orundefined
is provided, the function removes the current maximum pitch (sets it to 60).
Returns Map this
getMaxPitch
Returns the map’s maximum allowable pitch.
Returns number maxPitch
getRenderWorldCopies
Returns the state of renderWorldCopies
. If true
, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to false
:
- When the map is zoomed out far enough that a single representation of the world does not fill the map’s entire container, there will be blank space beyond 180 and -180 degrees longitude.
- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level.
Examples
var worldCopiesRendered = map.getRenderWorldCopies();
Returns boolean renderWorldCopies
setRenderWorldCopies
Sets the state of renderWorldCopies
.
Parameters
renderWorldCopies
boolean Iftrue
, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set tofalse
:- When the map is zoomed out far enough that a single representation of the world does not fill the map’s entire container, there will be blank space beyond 180 and -180 degrees longitude.- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
map and the other on the left edge of the map) at every zoom level.
undefined
is treated astrue
,null
is treated asfalse
.
- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
map and the other on the left edge of the map) at every zoom level.
Examples
map.setRenderWorldCopies(true);
Returns Map this
project
Returns a Point representing pixel coordinates, relative to the map’s container
,
that correspond to the specified geographical location.
Parameters
lnglat
LngLatLike The geographical location to project.
Examples
var coordinate = [-122.420679, 37.772537];
var point = map.project(coordinate);
Returns Point The Point corresponding to lnglat
, relative to the map’s container
.
unproject
Returns a LngLat representing geographical coordinates that correspond to the specified pixel coordinates.
Parameters
point
PointLike The pixel coordinates to unproject.
Examples
map.on('click', function(e) {
// When the map is clicked, get the geographic coordinate.
var coordinate = map.unproject(e.point);
});
Returns LngLat The LngLat corresponding to point
.
isMoving
Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.
Examples
var isMoving = map.isMoving();
Returns boolean True if the map is moving.
isZooming
Returns true if the map is zooming due to a camera animation or user gesture.
Examples
var isZooming = map.isZooming();
Returns boolean True if the map is zooming.
isRotating
Returns true if the map is rotating due to a camera animation or user gesture.
Examples
map.isRotating();
Returns boolean True if the map is rotating.
on
Adds a listener for events of a specified type, optionally limited to features in a specified style layer.
Parameters
-
type
string The event type to listen for. Events compatible with the optionallayerId
parameter are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.Event Compatible with layerId
mousedown
yes mouseup
yes mouseover
yes mouseout
yes mousemove
yes mouseenter
yes (required) mouseleave
yes (required) click
yes dblclick
yes contextmenu
yes touchstart
yes touchend
yes touchcancel
yes wheel
resize
remove
touchmove
movestart
move
moveend
dragstart
drag
dragend
zoomstart
zoom
zoomend
rotatestart
rotate
rotateend
pitchstart
pitch
pitchend
boxzoomstart
boxzoomend
boxzoomcancel
webglcontextlost
webglcontextrestored
load
render
idle
error
data
styledata
sourcedata
dataloading
styledataloading
sourcedataloading
styleimagemissing
layerId
string (optional) The ID of a style layer. Event will only be triggered if its location is within a visible feature in this layer. The event will have afeatures
property containing an array of the matching features. IflayerId
is not supplied, the event will not have afeatures
property. Please note that many event types are not compatible with the optionallayerId
parameter.listener
Function The function to be called when the event is fired.
Examples
// Set an event listener that will fire
// when the map has finished loading
map.on('load', function() {
// Once the map has finished loading,
// add a new layer
map.addLayer({
id: 'points-of-interest',
source: {
type: 'vector',
url: 'mapbox://mapbox.mapbox-streets-v8'
},
'source-layer': 'poi_label',
type: 'circle',
paint: {
// Mapbox Style Specification paint properties
},
layout: {
// Mapbox Style Specification layout properties
}
});
});
// Set an event listener that will fire
// when a feature on the countries layer of the map is clicked
map.on('click', 'countries', function(e) {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(`Country name: ${e.features[0].properties.name}`)
.addTo(map);
});
Returns Map this
once
Adds a listener that will be called only once to a specified event type.
Parameters
type
string The event type to add a listener for.listener
Function The function to be called when the event is fired. The listener function is called with the data object passed tofire
, extended withtarget
andtype
properties.
Returns Map this
once
Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer.
Parameters
type
string The event type to listen for; one of'mousedown'
,'mouseup'
,'click'
,'dblclick'
,'mousemove'
,'mouseenter'
,'mouseleave'
,'mouseover'
,'mouseout'
,'contextmenu'
,'touchstart'
,'touchend'
, or'touchcancel'
.mouseenter
andmouseover
events are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.mouseleave
andmouseout
events are triggered when the cursor leaves a visible portion of the specified layer, or leaves the map canvas.layerId
string The ID of a style layer. Only events whose location is within a visible feature in this layer will trigger the listener. The event will have afeatures
property containing an array of the matching features.listener
Function The function to be called when the event is fired.
Returns Map this
off
Removes an event listener previously added with Map#on
.
Parameters
type
string The event type previously used to install the listener.listener
Function The function previously installed as a listener.
Returns Map this
off
Removes an event listener for layer-specific events previously added with Map#on
.
Parameters
type
string The event type previously used to install the listener.layerId
string The layer ID previously used to install the listener.listener
Function The function previously installed as a listener.
Returns Map this
queryRenderedFeatures
Returns an array of GeoJSON Feature objects representing visible features that satisfy the query parameters.
Parameters
geometry
(PointLike | Array<PointLike>)? The geometry of the query region: either a single point or southwest and northeast points describing a bounding box. Omitting this parameter (i.e. calling Map#queryRenderedFeatures with zero arguments, or with only aoptions
argument) is equivalent to passing a bounding box encompassing the entire map viewport.options
Object? Options object.options.layers
Array<string>? An array of style layer IDs for the query to inspect. Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.options.filter
Array? A filter to limit query results.options.validate
boolean Whether to check if the [options.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. (optional, defaulttrue
)
Examples
// Find all features at a point
var features = map.queryRenderedFeatures(
[20, 35],
{ layers: ['my-layer-name'] }
);
// Find all features within a static bounding box
var features = map.queryRenderedFeatures(
[[10, 20], [30, 50]],
{ layers: ['my-layer-name'] }
);
// Find all features within a bounding box around a point
var width = 10;
var height = 20;
var features = map.queryRenderedFeatures([
[point.x - width / 2, point.y - height / 2],
[point.x + width / 2, point.y + height / 2]
], { layers: ['my-layer-name'] });
// Query all rendered features from a single layer
var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });
Returns Array<Object> An array of GeoJSON
feature objects.The properties
value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only
string and numeric property values are supported (i.e. null
, Array
, and Object
values are not supported).Each feature includes top-level layer
, source
, and sourceLayer
properties. The layer
property is an object
representing the style layer to which the feature belongs. Layout and paint properties in this object contain values
which are fully evaluated for the given zoom level and feature.Only features that are currently rendered are included. Some features will not be included, like:- Features from layers whose visibility
property is "none"
.
- Features from layers whose zoom range excludes the current zoom level.
- Symbol features that have been hidden due to text or icon collision.Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer’s opacity or color alpha component is set to 0.The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low zoom levels) are returned only once (though subject to the following caveat).Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.
querySourceFeatures
Returns an array of GeoJSON Feature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
Parameters
sourceId
string The ID of the vector tile or GeoJSON source to query.parameters
Object? Options object.parameters.sourceLayer
string? The name of the source layer to query. For vector tile sources, this parameter is required. For GeoJSON sources, it is ignored.parameters.filter
Array? A filter to limit query results.parameters.validate
boolean Whether to check if the [parameters.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. (optional, defaulttrue
)
Examples
// Find all features in one source layer in a vector source
var features = map.querySourceFeatures('your-source-id', {
sourceLayer: 'your-source-layer'
});
Returns Array<Object> An array of GeoJSON Feature objects.In contrast to Map#queryRenderedFeatures, this function returns all features matching the query parameters, whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently visible viewport.Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.
setStyle
Updates the map’s Mapbox style object with a new value.
If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style against the map’s current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites (images used for icons and patterns) and glyphs (fonts for label text) cannot be diffed. If the sprites or fonts used in the current style and the given style are different in any way, the map renderer will force a full update, removing the current style and building the given one from scratch.
Parameters
style
(StyleSpecification | string | null) A JSON object conforming to the schema described in the Mapbox Style Specification, or a URL to such JSON.options
Object? Options object.options.diff
boolean If false, force a ‘full’ update, removing the current style and building the given one instead of attempting a diff-based update. (optional, defaulttrue
)options.localIdeographFontFamily
string Defines a CSS font-family for locally overriding generation of glyphs in the ‘CJK Unified Ideographs’, ‘Hiragana’, ‘Katakana’ and ‘Hangul Syllables’ ranges. In these ranges, font settings from the map’s style will be ignored, except for font-weight keywords (light/regular/medium/bold). Set tofalse
, to enable font settings from the map’s style for these glyph ranges. Forces a full update. (optional, default'sans-serif'
)
Examples
map.setStyle("mapbox://styles/mapbox/streets-v11");
Returns Map this
getStyle
Returns the map’s Mapbox style object, a JSON object which can be used to recreate the map’s style.
Examples
var styleJson = map.getStyle();
Returns Object The map’s style JSON object.
isStyleLoaded
Returns a Boolean indicating whether the map’s style is fully loaded.
Examples
var styleLoadStatus = map.isStyleLoaded();
Returns boolean A Boolean indicating whether the style is fully loaded.
addSource
- **See: Vector source: Show and hide layers **
- **See: GeoJSON source: Add live realtime data **
- **See: Raster DEM source: Add hillshading **
Adds a source to the map’s style.
Parameters
id
string The ID of the source to add. Must not conflict with existing sources.source
Object The source object, conforming to the Mapbox Style Specification’s source definition or CanvasSourceOptions.
Examples
map.addSource('my-data', {
type: 'vector',
url: 'mapbox://myusername.tilesetid'
});
map.addSource('my-data', {
"type": "geojson",
"data": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-77.0323, 38.9131]
},
"properties": {
"title": "Mapbox DC",
"marker-symbol": "monument"
}
}
});
Returns Map this
isSourceLoaded
Returns a Boolean indicating whether the source is loaded. Returns true
if the source with
the given ID in the map’s style has no outstanding network requests, otherwise false
.
Parameters
id
string The ID of the source to be checked.
Examples
var sourceLoaded = map.isSourceLoaded('bathymetry-data');
Returns boolean A Boolean indicating whether the source is loaded.
areTilesLoaded
Returns a Boolean indicating whether all tiles in the viewport from all sources on the style are loaded.
Examples
var tilesLoaded = map.areTilesLoaded();
Returns boolean A Boolean indicating whether all tiles are loaded.
removeSource
Removes a source from the map’s style.
Parameters
id
string The ID of the source to remove.
Examples
map.removeSource('bathymetry-data');
Returns Map this
getSource
Returns the source with the specified ID in the map’s style.
This method is often used to update a source using the instance members for the relevant
source type as defined in Sources.
For example, setting the data
for a GeoJSON source or updating the url
and coordinates
of an image source.
Parameters
id
string The ID of the source to get.
Examples
var sourceObject = map.getSource('points');
Returns Object? The style source with the specified ID or undefined
if the ID
corresponds to no existing sources.
The shape of the object varies by source type.
A list of options for each source type is available on the Mapbox Style Specification’s
Sources page.
addImage
- **See: Use
HTMLImageElement
: Add an icon to the map ** - **See: Use
ImageData
: Add a generated icon to the map **
Add an image to the style. This image can be displayed on the map like any other icon in the style’s
sprite using the image’s ID with
icon-image
,
background-pattern
,
fill-pattern
,
or line-pattern
.
A Map.event:error event will be fired if there is not enough space in the sprite to add this image.
Parameters
id
string The ID of the image.image
(HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface) The image as anHTMLImageElement
,ImageData
,ImageBitmap
or object withwidth
,height
, anddata
properties with the same format asImageData
.options
$Shape<StyleImageMetadata> Options object. (optional, default{}
)options.pixelRatio
The ratio of pixels in the image to physical pixels on the screen (optional, default1
)options.sdf
Whether the image should be interpreted as an SDF image (optional, defaultfalse
)options.stretchX
[[x1, x2], ...]
Ificon-text-fit
is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally.options.stretchY
[[y1, y2], ...]
Ificon-text-fit
is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically.options.content
[x1, y1, x2, y2]
Ificon-text-fit
is used in a layer with this image, this option defines the part of the image that can be covered by the content intext-field
.
Examples
// If the style's sprite does not already contain an image with ID 'cat',
// add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) {
if (error) throw error;
if (!map.hasImage('cat')) map.addImage('cat', image);
});
// Add a stretchable image that can be used with `icon-text-fit`
// In this example, the image is 600px wide by 400px high.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) {
if (error) throw error;
if (!map.hasImage('border-image')) {
map.addImage('border-image', image, {
content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border
stretchX: [[16, 584]], // stretch everything horizontally except the 16px border
stretchY: [[16, 384]], // stretch everything vertically except the 16px border
});
}
});
updateImage
Update an existing image in a style. This image can be displayed on the map like any other icon in the style’s
sprite using the image’s ID with
icon-image
,
background-pattern
,
fill-pattern
,
or line-pattern
.
Parameters
id
string The ID of the image.image
(HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface) The image as anHTMLImageElement
,ImageData
,ImageBitmap
or object withwidth
,height
, anddata
properties with the same format asImageData
.
Examples
// If an image with the ID 'cat' already exists in the style's sprite,
// replace that image with a new image, 'other-cat-icon.png'.
if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');
hasImage
Check whether or not an image with a specific ID exists in the style. This checks both images in the style’s original sprite and any images that have been added at runtime using Map#addImage.
Parameters
id
string The ID of the image.
Examples
// Check if an image with the ID 'cat' exists in
// the style's sprite.
var catIconExists = map.hasImage('cat');
Returns boolean A Boolean indicating whether the image exists.
removeImage
Remove an image from a style. This can be an image from the style’s original sprite or any images that have been added at runtime using Map#addImage.
Parameters
id
string The ID of the image.
Examples
// If an image with the ID 'cat' exists in
// the style's sprite, remove it.
if (map.hasImage('cat')) map.removeImage('cat');
loadImage
Load an image from an external URL to be used with Map#addImage. External domains must support CORS.
Parameters
url
string The URL of the image file. Image file must be in png, webp, or jpg format.callback
Function Expectingcallback(error, data)
. Called when the image has loaded or with an error argument if there is an error.
Examples
// Load an image from an external URL.
map.loadImage('http://placekitten.com/50/50', function(error, image) {
if (error) throw error;
// Add the loaded image to the style's sprite with the ID 'kitten'.
map.addImage('kitten', image);
});
listImages
Returns an Array of strings containing the IDs of all images currently available in the map. This includes both images from the style’s original sprite and any images that have been added at runtime using Map#addImage.
Examples
var allImages = map.listImages();
Returns Array<string> An Array of strings containing the names of all sprites/images currently available in the map.
addLayer
Adds a Mapbox style layer to the map’s style.
A layer defines how data from a specified source will be styled. Read more about layer types and available paint and layout properties in the Mapbox Style Specification.
Parameters
layer
(Object | CustomLayerInterface) The layer to add, conforming to either the Mapbox Style Specification’s layer definition or, less commonly, the CustomLayerInterface specification. The Mapbox Style Specification’s layer definition is appropriate for most layers.layer.id
string A unique idenfier that you define.layer.type
string The type of layer (for examplefill
orsymbol
). A list of layer types is available in the Mapbox Style Specification.(This can also becustom
. For more information, see CustomLayerInterface.)layer.source
(string | Object)? The data source for the layer. Reference a source that has already been defined using the source’s unique id. Reference a new source using a source object (as defined in the Mapbox Style Specification) directly. This is required for alllayer.type
options except forcustom
.layer.sourceLayer
string? (optional) The name of the source layer within the specifiedlayer.source
to use for this style layer. This is only applicable for vector tile sources and is required whenlayer.source
is of the typevector
.layer.filter
array? (optional) An expression specifying conditions on source features. Only features that match the filter are displayed. The Mapbox Style Specification includes more information on the limitations of thefilter
parameter and a complete list of available expressions. If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed.layer.paint
Object? (optional) Paint properties for the layer. Available paint properties vary bylayer.type
. A full list of paint properties for each layer type is available in the Mapbox Style Specification. If no paint properties are specified, default values will be used.layer.layout
Object? (optional) Layout properties for the layer. Available layout properties vary bylayer.type
. A full list of layout properties for each layer type is available in the Mapbox Style Specification. If no layout properties are specified, default values will be used.layer.maxzoom
number? (optional) The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden. The value can be any number between0
and24
(inclusive). If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.layer.minzoom
number? (optional) The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden. The value can be any number between0
and24
(inclusive). If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.layer.metadata
Object? (optional) Arbitrary properties useful to track with the layer, but do not influence rendering.layer.renderingMode
string? This is only applicable for layers with the typecustom
. See CustomLayerInterface for more information.
beforeId
string? The ID of an existing layer to insert the new layer before, resulting in the new layer appearing visually beneath the existing layer. If this argument is not specified, the layer will be appended to the end of the layers array and appear visually above all other layers.
Examples
// Add a circle layer with a vector source
map.addLayer({
id: 'points-of-interest',
source: {
type: 'vector',
url: 'mapbox://mapbox.mapbox-streets-v8'
},
'source-layer': 'poi_label',
type: 'circle',
paint: {
// Mapbox Style Specification paint properties
},
layout: {
// Mapbox Style Specification layout properties
}
});
// Define a source before using it to create a new layer
map.addSource('state-data', {
type: 'geojson',
data: 'path/to/data.geojson'
});
map.addLayer({
id: 'states',
// References the GeoJSON source defined above
// and does not require a `source-layer`
source: 'state-data',
type: 'symbol',
layout: {
// Set the label content to the
// feature's `name` property
text-field: ['get', 'name']
}
});
// Add a new symbol layer before an existing layer
map.addLayer({
id: 'states',
// References a source that's already been defined
source: 'state-data',
type: 'symbol',
layout: {
// Set the label content to the
// feature's `name` property
text-field: ['get', 'name']
}
// Add the layer before the existing `cities` layer
}, 'cities');
Returns Map this
moveLayer
Moves a layer to a different z-position.
Parameters
id
string The ID of the layer to move.beforeId
string? The ID of an existing layer to insert the new layer before. When viewing the map, theid
layer will appear beneath thebeforeId
layer. IfbeforeId
is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.
Examples
// Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map.
map.moveLayer('polygon', 'country-label');
Returns Map this
removeLayer
Removes the layer with the given ID from the map’s style.
If no such layer exists, an error
event is fired.
Parameters
id
string id of the layer to remove
Examples
// If a layer with ID 'state-data' exists, remove it.
if (map.getLayer('state-data')) map.removeLayer('state-data');
getLayer
Returns the layer with the specified ID in the map’s style.
Parameters
id
string The ID of the layer to get.
Examples
var stateDataLayer = map.getLayer('state-data');
Returns Object? The layer with the specified ID, or undefined
if the ID corresponds to no existing layers.
setLayerZoomRange
Sets the zoom extent for the specified style layer. The zoom extent includes the minimum zoom level and maximum zoom level) at which the layer will be rendered.
Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the minimum zoom level of the source layer because the data does not exist at those zoom levels. If the minimum zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style layer will not be rendered at all zoom levels in the zoom range.
Parameters
layerId
string The ID of the layer to which the zoom extent will be applied.minzoom
number The minimum zoom to set (0-24).maxzoom
number The maximum zoom to set (0-24).
Examples
map.setLayerZoomRange('my-layer', 2, 5);
Returns Map this
setFilter
- **See: Tutorial: Show changes over time **
Sets the filter for the specified style layer.
Filters control which features a style layer renders from its source.
Any feature for which the filter expression evaluates to true
will be
rendered on the map. Those that are false will be hidden.
Use setFilter
to show a subset of your source data.
To clear the filter, pass null
or undefined
as the second parameter.
Parameters
layerId
string The ID of the layer to which the filter will be applied.filter
(Array | null | undefined) The filter, conforming to the Mapbox Style Specification’s filter definition. Ifnull
orundefined
is provided, the function removes any existing filter from the layer.options
Object? Options object. (optional, default{}
)options.validate
boolean Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. (optional, defaulttrue
)
Examples
// display only features with the 'name' property 'USA'
map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);
// display only features with five or more 'available-spots'
map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);
// remove the filter for the 'bike-docks' style layer
map.setFilter('bike-docks', null);
Returns Map this
getFilter
Returns the filter applied to the specified style layer.
Parameters
layerId
string The ID of the style layer whose filter to get.
Returns Array The layer’s filter.
setPaintProperty
Sets the value of a paint property in the specified style layer.
Parameters
layerId
string The ID of the layer to set the paint property in.name
string The name of the paint property to set.value
any The value of the paint property to set. Must be of a type appropriate for the property, as defined in the Mapbox Style Specification.options
Object? Options object. (optional, default{}
)options.validate
boolean Whether to check ifvalue
conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. (optional, defaulttrue
)
Examples
map.setPaintProperty('my-layer', 'fill-color', '#faafee');
Returns Map this
getPaintProperty
Returns the value of a paint property in the specified style layer.
Parameters
layerId
string The ID of the layer to get the paint property from.name
string The name of a paint property to get.
Returns any The value of the specified paint property.
setLayoutProperty
Sets the value of a layout property in the specified style layer.
Parameters
layerId
string The ID of the layer to set the layout property in.name
string The name of the layout property to set.value
any The value of the layout property. Must be of a type appropriate for the property, as defined in the Mapbox Style Specification.options
Object? Options object. (optional, default{}
)options.validate
boolean Whether to check ifvalue
conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. (optional, defaulttrue
)
Examples
map.setLayoutProperty('my-layer', 'visibility', 'none');
Returns Map this
getLayoutProperty
Returns the value of a layout property in the specified style layer.
Parameters
layerId
string The ID of the layer to get the layout property from.name
string The name of the layout property to get.
Returns any The value of the specified layout property.
setLight
Sets the any combination of light values.
Parameters
light
LightSpecification Light properties to set. Must conform to the Mapbox Style Specification.options
Object? Options object. (optional, default{}
)options.validate
boolean Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. (optional, defaulttrue
)
Examples
var layerVisibility = map.getLayoutProperty('my-layer', 'visibility');
Returns Map this
getLight
Returns the value of the light object.
Returns Object light Light properties of the style.
setFeatureState
- **See: Tutorial: Create interactive hover effects with Mapbox GL JS **
Sets the state
of a feature.
A feature’s state
is a set of user-defined key-value pairs that are assigned to a feature at runtime.
When using this method, the state
object is merged with any existing key-value pairs in the feature’s state.
Features are identified by their feature.id
attribute, which can be any number or string.
This method can only be used with sources that have a feature.id
attribute. The feature.id
attribute can be defined in three ways:
- For vector or GeoJSON sources, including an
id
attribute in the original data file. - For vector or GeoJSON sources, using the
promoteId
option at the time the source is defined. - For GeoJSON sources, using the
generateId
option to auto-assign anid
based on the feature’s index in the source data. If you change feature data usingmap.getSource('some id').setData(..)
, you may need to re-apply state taking into account updatedid
values.
Note: You can use the feature-state
expression to access the values in a feature’s state object for the purposes of styling.
Parameters
feature
Object Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.state
Object A set of key-value pairs. The values should be valid JSON types.
Examples
// When the mouse moves over the `my-layer` layer, update
// the feature state for the feature under the mouse
map.on('mousemove', 'my-layer', function(e) {
if (e.features.length > 0) {
map.setFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id,
}, {
hover: true
});
}
});
removeFeatureState
Removes the state
of a feature, setting it back to the default behavior.
If only a target.source
is specified, it will remove the state for all features from that source.
If target.id
is also specified, it will remove all keys for that feature’s state.
If key
is also specified, it removes only that key from that feature’s state.
Features are identified by their feature.id
attribute, which can be any number or string.
Parameters
target
Object Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.key
string (optional) The key in the feature state to reset.
Examples
// Reset the entire state object for all features
// in the `my-source` source
map.removeFeatureState({
source: 'my-source'
});
// When the mouse leaves the `my-layer` layer,
// reset the entire state object for the
// feature under the mouse
map.on('mouseleave', 'my-layer', function(e) {
map.removeFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id
});
});
// When the mouse leaves the `my-layer` layer,
// reset only the `hover` key-value pair in the
// state for the feature under the mouse
map.on('mouseleave', 'my-layer', function(e) {
map.removeFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id
}, 'hover');
});
getFeatureState
Gets the state
of a feature.
A feature’s state
is a set of user-defined key-value pairs that are assigned to a feature at runtime.
Features are identified by their feature.id
attribute, which can be any number or string.
Note: To access the values in a feature’s state object for the purposes of styling the feature, use the feature-state
expression.
Parameters
feature
Object Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.
Examples
// When the mouse moves over the `my-layer` layer,
// get the feature state for the feature under the mouse
map.on('mousemove', 'my-layer', function(e) {
if (e.features.length > 0) {
map.getFeatureState({
source: 'my-source',
sourceLayer: 'my-source-layer',
id: e.features[0].id
});
}
});
Returns Object The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.
getContainer
Returns the map’s containing HTML element.
Returns HTMLElement The map’s container.
getCanvasContainer
Returns the HTML element containing the map’s <canvas>
element.
If you want to add non-GL overlays to the map, you should append them to this element.
This is the element to which event bindings for map interactivity (such as panning and zooming) are
attached. It will receive bubbled events from child elements such as the <canvas>
, but not from
map controls.
Returns HTMLElement The container of the map’s <canvas>
.
getCanvas
Returns the map’s <canvas>
element.
Returns HTMLCanvasElement The map’s <canvas>
element.
loaded
Returns a Boolean indicating whether the map is fully loaded.
Returns false
if the style is not yet fully loaded,
or if there has been a change to the sources or style that
has not yet fully loaded.
Returns boolean A Boolean indicating whether the map is fully loaded.
remove
Clean up and release all internal resources associated with this map.
This includes DOM elements, event bindings, web workers, and WebGL resources.
Use this method when you are done using the map and wish to ensure that it no longer consumes browser resources. Afterwards, you must not call any other methods on the map.
triggerRepaint
Trigger the rendering of a single frame. Use this method with custom layers to repaint the map when the layer changes. Calling this multiple times before the next frame is rendered will still result in only a single frame being rendered.
Examples
map.triggerRepaint();
showTileBoundaries
Gets and sets a Boolean indicating whether the map will render an outline around each tile and the tile ID. These tile boundaries are useful for debugging.
The uncompressed file size of the first vector source is drawn in the top left corner of each tile, next to the tile ID.
Type: boolean
Examples
map.showTileBoundaries = true;
showPadding
Gets and sets a Boolean indicating whether the map will visualize the padding offsets.
Type: boolean
showCollisionBoxes
Gets and sets a Boolean indicating whether the map will render boxes around all symbols in the data source, revealing which symbols were rendered or which were hidden due to collisions. This information is useful for debugging.
Type: boolean
repaint
Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance.
Type: boolean
version
The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.
Type: string
getCenter
- **See: Tutorial: Use Mapbox GL JS in a React app **
Returns the map’s geographical centerpoint.
Examples
// return a LngLat object such as {lng: 0, lat: 0}
var center = map.getCenter();
// access longitude and latitude values directly
var {longitude, latitude} = map.getCenter();
Returns LngLat The map’s geographical centerpoint.
setCenter
Sets the map’s geographical centerpoint. Equivalent to jumpTo({center: center})
.
Parameters
center
LngLatLike The centerpoint to set.eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
map.setCenter([-74, 38]);
Returns Map this
panBy
Pans the map by the specified offset.
Parameters
offset
PointLikex
andy
coordinates by which to pan the map.options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
panTo
Pans the map to the specified location with an animated transition.
Parameters
lnglat
LngLatLike The location to pan the map to.options
AnimationOptions? Options describing the destination and animation of the transition.eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
map.panTo([-74, 38]);
// Specify that the panTo animation should last 5000 milliseconds.
map.panTo([-74, 38], {duration: 5000});
Returns Map this
getZoom
Returns the map’s current zoom level.
Examples
map.getZoom();
Returns number The map’s current zoom level.
setZoom
Sets the map’s zoom level. Equivalent to jumpTo({zoom: zoom})
.
Parameters
zoom
number The zoom level to set (0-20).eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// Zoom to the zoom level 5 without an animated transition
map.setZoom(5);
Returns Map this
zoomTo
Zooms the map to the specified zoom level, with an animated transition.
Parameters
zoom
number The zoom level to transition to.options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// Zoom to the zoom level 5 without an animated transition
map.zoomTo(5);
// Zoom to the zoom level 8 with an animated transition
map.zoomTo(8, {
duration: 2000,
offset: [100, 50]
});
Returns Map this
zoomIn
Increases the map’s zoom level by 1.
Parameters
options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// zoom the map in one level with a custom animation duration
map.zoomIn({duration: 1000});
Returns Map this
zoomOut
Decreases the map’s zoom level by 1.
Parameters
options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// zoom the map out one level with a custom animation offset
map.zoomOut({offset: [80, 60]});
Returns Map this
getBearing
Returns the map’s current bearing. The bearing is the compass direction that is “up”; for example, a bearing of 90° orients the map so that east is up.
Returns number The map’s current bearing.
setBearing
Sets the map’s bearing (rotation). The bearing is the compass direction that is “up”; for example, a bearing of 90° orients the map so that east is up.
Equivalent to jumpTo({bearing: bearing})
.
Parameters
bearing
number The desired bearing.eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// rotate the map to 90 degrees
map.setBearing(90);
Returns Map this
getPadding
Returns the current padding applied around the map viewport.
Returns PaddingOptions The current padding around the map viewport.
setPadding
Sets the padding in pixels around the viewport.
Equivalent to jumpTo({padding: padding})
.
Parameters
padding
PaddingOptions The desired padding. Format: { left: number, right: number, top: number, bottom: number }eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// Sets a left padding of 300px, and a top padding of 50px
map.setPadding({ left: 300, top: 50 });
Returns Map this
rotateTo
Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.
Parameters
bearing
number The desired bearing.options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
resetNorth
Rotates the map so that north is up (0° bearing), with an animated transition.
Parameters
options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
resetNorthPitch
Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.
Parameters
options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
snapToNorth
Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the
bearingSnap
threshold).
Parameters
options
AnimationOptions? Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
getPitch
Returns the map’s current pitch (tilt).
Returns number The map’s current pitch, measured in degrees away from the plane of the screen.
setPitch
Sets the map’s pitch (tilt). Equivalent to jumpTo({pitch: pitch})
.
Parameters
pitch
number The pitch to set, measured in degrees away from the plane of the screen (0-60).eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
cameraForBounds
Parameters
bounds
LngLatBoundsLike Calculate the center for these bounds in the viewport and use the highest zoom level up to and includingMap#getMaxZoom()
that fits in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.options
CameraOptions? Options object-
options.padding
**(numberPaddingOptions)?** The amount of padding in pixels to add to the given bounds. options.bearing
number Desired map bearing at end of animation, in degrees. (optional, default0
)options.offset
PointLike The center of the given bounds relative to the map’s center, measured in pixels. (optional, default[0,0]
)options.maxZoom
number? The maximum zoom level to allow when the camera would transition to the specified bounds.
-
Examples
var bbox = [[-79, 43], [-73, 45]];
var newCameraTransform = map.cameraForBounds(bbox, {
padding: {top: 10, bottom:25, left: 15, right: 5}
});
Returns (CameraOptions | void) If map is able to fit to provided bounds, returns CameraOptions
with
center
, zoom
, and bearing
. If map is unable to fit, method will warn and return undefined.
fitBounds
Pans and zooms the map to contain its visible area within the specified geographical bounds. This function will also reset the map’s bearing to 0 if bearing is nonzero.
Parameters
bounds
LngLatBoundsLike Center these bounds in the viewport and use the highest zoom level up to and includingMap#getMaxZoom()
that fits them in the viewport.options
Object? Options supports all properties from AnimationOptions and CameraOptions in addition to the fields below.-
options.padding
**(numberPaddingOptions)?** The amount of padding in pixels to add to the given bounds. options.linear
boolean Iftrue
, the map transitions using Map#easeTo. Iffalse
, the map transitions using Map#flyTo. See those functions and AnimationOptions for information about options available. (optional, defaultfalse
)options.easing
Function? An easing function for the animated transition. See AnimationOptions.options.offset
PointLike The center of the given bounds relative to the map’s center, measured in pixels. (optional, default[0,0]
)options.maxZoom
number? The maximum zoom level to allow when the map view transitions to the specified bounds.
-
eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
var bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
padding: {top: 10, bottom:25, left: 15, right: 5}
});
Returns Map this
fitScreenCoordinates
- **See: Used by BoxZoomHandler **
Pans, rotates and zooms the map to to fit the box made by points p0 and p1 once the map is rotated to the specified bearing. To zoom without rotating, pass in the current map bearing.
Parameters
p0
PointLike First point on screen, in pixel coordinatesp1
PointLike Second point on screen, in pixel coordinatesbearing
number Desired map bearing at end of animation, in degreesoptions
any? Options object-
options.padding
**(numberPaddingOptions)?** The amount of padding in pixels to add to the given bounds. options.linear
boolean Iftrue
, the map transitions using Map#easeTo. Iffalse
, the map transitions using Map#flyTo. See those functions and AnimationOptions for information about options available. (optional, defaultfalse
)options.easing
Function? An easing function for the animated transition. See AnimationOptions.options.offset
PointLike The center of the given bounds relative to the map’s center, measured in pixels. (optional, default[0,0]
)options.maxZoom
number? The maximum zoom level to allow when the map view transitions to the specified bounds.
-
eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
var p0 = [220, 400];
var p1 = [500, 900];
map.fitScreenCoordinates(p0, p1, map.getBearing(), {
padding: {top: 10, bottom:25, left: 15, right: 5}
});
Returns Map this
jumpTo
Changes any combination of center, zoom, bearing, and pitch, without
an animated transition. The map will retain its current values for any
details not specified in options
.
Parameters
options
CameraOptions Options objecteventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// jump to coordinates at current zoom
map.jumpTo({center: [0, 0]});
// jump with zoom, pitch, and bearing options
map.jumpTo({
center: [0, 0],
zoom: 8,
pitch: 45,
bearing: 90
});
Returns Map this
easeTo
Changes any combination of center
, zoom
, bearing
, pitch
, and padding
with an animated transition
between old and new values. The map will retain its current values for any
details not specified in options
.
Note: The transition will happen instantly if the user has enabled
the reduced motion
accesibility feature enabled in their operating system,
unless options
includes essential: true
.
Parameters
options
any Options describing the destination and animation of the transition. Accepts CameraOptions and AnimationOptions.eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Returns Map this
flyTo
Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that evokes flight. The animation seamlessly incorporates zooming and panning to help the user maintain her bearings even after traversing a great distance.
Note: The animation will be skipped, and this will behave equivalently to jumpTo
if the user has the reduced motion
accesibility feature enabled in their operating system,
unless ‘options’ includes essential: true
.
Parameters
options
Object Options describing the destination and animation of the transition. Accepts CameraOptions, AnimationOptions, and the following additional options.options.curve
number The zooming “curve” that will occur along the flight path. A high value maximizes zooming for an exaggerated animation, while a low value minimizes zooming for an effect closer to Map#easeTo. 1.42 is the average value selected by participants in the user study discussed in van Wijk (2003). A value ofMath.pow(6, 0.25)
would be equivalent to the root mean squared average velocity. A value of 1 would produce a circular motion. (optional, default1.42
)options.minZoom
number? The zero-based zoom level at the peak of the flight path. Ifoptions.curve
is specified, this option is ignored.options.speed
number The average speed of the animation defined in relation tooptions.curve
. A speed of 1.2 means that the map appears to move along the flight path by 1.2 timesoptions.curve
screenfuls every second. A screenful is the map’s visible span. It does not correspond to a fixed physical distance, but varies by zoom level. (optional, default1.2
)options.screenSpeed
number? The average speed of the animation measured in screenfuls per second, assuming a linear timing curve. Ifoptions.speed
is specified, this option is ignored.options.maxDuration
number? The animation’s maximum duration, measured in milliseconds. If duration exceeds maximum duration, it resets to 0.
eventData
Object? Additional properties to be added to event objects of events triggered by this method.
Examples
// fly with default options to null island
map.flyTo({center: [0, 0], zoom: 9});
// using flyTo options
map.flyTo({
center: [0, 0],
zoom: 9,
speed: 0.2,
curve: 1,
easing(t) {
return t;
}
});
Returns Map this
stop
Stops any animated transition underway.
Returns Map this
resize
Fired immediately after the map has been resized.
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// immediately after the map has been resized.
map.on('resize', function() {
console.log('A resize event occurred.');
});
remove
Fired immediately after the map has been removed with Map.event:remove.
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just after the map is removed.
map.on('remove', function() {
console.log('A remove event occurred.');
});
mousedown
Fired when a pointing device (usually a mouse) is pressed within the map.
Note: This event is compatible with the optional layerId
parameter.
If layerId
is included as the second argument in Map#on, the event listener will fire only when the
the cursor is pressed while inside a visible portion of the specifed layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('mousedown', function() {
console.log('A mousedown event has occurred.');
});
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mousedown', 'poi-label', function() {
console.log('A mousedown event has occurred on a visible portion of the poi-label layer.');
});
mouseup
Fired when a pointing device (usually a mouse) is released within the map.
Note: This event is compatible with the optional layerId
parameter.
If layerId
is included as the second argument in Map#on, the event listener will fire only when the
the cursor is released while inside a visible portion of the specifed layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('mouseup', function() {
console.log('A mouseup event has occurred.');
});
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mouseup', 'poi-label', function() {
console.log('A mouseup event has occurred on a visible portion of the poi-label layer.');
});
mouseover
Fired when a pointing device (usually a mouse) is moved within the map. As you move the cursor across a web page containing a map, the event will fire each time it enters the map or any child elements.
Note: This event is compatible with the optional layerId
parameter.
If layerId
is included as the second argument in Map#on, the event listener will fire only when the
the cursor is moved inside a visible portion of the specifed layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('mouseover', function() {
console.log('A mouseover event has occurred.');
});
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mouseover', 'poi-label', function() {
console.log('A mouseover event has occurred on a visible portion of the poi-label layer.');
});
mousemove
Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map. As you move the cursor across the map, the event will fire every time the cursor changes position within the map.
Note: This event is compatible with the optional layerId
parameter.
If layerId
is included as the second argument in Map#on, the event listener will fire only when the
the cursor is inside a visible portion of the specified layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('mousemove', function() {
console.log('A mousemove event has occurred.');
});
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('mousemove', 'poi-label', function() {
console.log('A mousemove event has occurred on a visible portion of the poi-label layer.');
});
click
Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.
Note: This event is compatible with the optional layerId
parameter.
If layerId
is included as the second argument in Map#on, the event listener will fire only when the
point that is pressed and released contains a visible portion of the specifed layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('click', function(e) {
console.log('A click event has occurred at ' + e.lngLat);
});
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('click', 'poi-label', function(e) {
console.log('A click event has occurred on a visible portion of the poi-label layer at ' + e.lngLat);
});
dblclick
Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession.
Note: This event is compatible with the optional layerId
parameter.
If layerId
is included as the second argument in Map#on, the event listener will fire only
when the point that is clicked twice contains a visible portion of the specifed layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('dblclick', function(e) {
console.log('A dblclick event has occurred at ' + e.lngLat);
});
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener for a specific layer
map.on('dblclick', 'poi-label', function(e) {
console.log('A dblclick event has occurred on a visible portion of the poi-label layer at ' + e.lngLat);
});
mouseenter
Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from outside that layer or outside the map canvas.
Important: This event can only be listened for when Map#on includes three arguments, where the second argument specifies the desired layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener
map.on('mouseenter', 'water', function() {
console.log('A mouseenter event occurred on a visible portion of the water layer.');
});
mouseleave
Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves the map canvas.
Important: This event can only be listened for when Map#on includes three arguements, where the second argument specifies the desired layer.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the pointing device leaves
// a visible portion of the specified layer.
map.on('mouseleave', 'water', function() {
console.log('A mouseleave event occurred.');
});
mouseout
Fired when a point device (usually a mouse) leaves the map’s canvas.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the pointing device leave's
// the map's canvas.
map.on('mouseout', function() {
console.log('A mouseout event occurred.');
});
contextmenu
Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.
Properties
data
MapMouseEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the right mouse button is
// pressed within the map.
map.on('contextmenu', function() {
console.log('A contextmenu event occurred.');
});
wheel
Fired when a wheel
event occurs within the map.
Properties
data
MapWheelEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when a wheel event occurs within the map.
map.on('wheel', function() {
console.log('A wheel event occurred.');
});
touchstart
Fired when a touchstart
event occurs within the map.
Properties
data
MapTouchEvent // Initialize the map var map = new mapboxgl.Map({ // map options }); // Set an event listener that fires // when a touchstart event occurs within the map. map.on(‘touchstart’, function() { console.log(‘A touchstart event occurred.’); });
touchend
Fired when a touchend
event occurs within the map.
Properties
data
MapTouchEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when a touchstart event occurs within the map.
map.on('touchstart', function() {
console.log('A touchstart event occurred.');
});
touchmove
Fired when a touchmove
event occurs within the map.
Properties
data
MapTouchEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when a touchmove event occurs within the map.
map.on('touchmove', function() {
console.log('A touchmove event occurred.');
});
touchcancel
Fired when a touchcancel
event occurs within the map.
Properties
data
MapTouchEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when a touchcancel event occurs within the map.
map.on('touchcancel', function() {
console.log('A touchcancel event occurred.');
});
movestart
Fired just before the map begins a transition from one view to another, as the result of either user interaction or methods such as Map#jumpTo.
Properties
data
{originalEvent: DragEvent}
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just before the map begins a transition
// from one view to another.
map.on('movestart', function() {
console.log('A movestart` event occurred.');
});
move
Fired repeatedly during an animated transition from one view to another, as the result of either user interaction or methods such as Map#flyTo.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during an animated transition.
map.on('move', function() {
console.log('A move event occurred.');
});
moveend
Fired just after the map completes a transition from one view to another, as the result of either user interaction or methods such as Map#jumpTo.
Properties
data
{originalEvent: DragEvent}
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just after the map completes a transition.
map.on('moveend', function() {
console.log('A moveend event occurred.');
});
dragstart
Fired when a “drag to pan” interaction starts. See DragPanHandler.
Properties
data
{originalEvent: DragEvent}
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when a "drag to pan" interaction starts.
map.on('dragstart', function() {
console.log('A dragstart event occurred.');
});
drag
Fired repeatedly during a “drag to pan” interaction. See DragPanHandler.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during a "drag to pan" interaction.
map.on('drag', function() {
console.log('A drag event occurred.');
});
dragend
Fired when a “drag to pan” interaction ends. See DragPanHandler.
Properties
data
{originalEvent: DragEvent}
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when a "drag to pan" interaction ends.
map.on('dragend', function() {
console.log('A dragend event occurred.');
});
zoomstart
Fired just before the map begins a transition from one zoom level to another, as the result of either user interaction or methods such as Map#flyTo.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just before a zoom transition starts.
map.on('zoomstart', function() {
console.log('A zoomstart event occurred.');
});
zoom
Fired repeatedly during an animated transition from one zoom level to another, as the result of either user interaction or methods such as Map#flyTo.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during a zoom transition.
map.on('zoom', function() {
console.log('A zoom event occurred.');
});
zoomend
Fired just after the map completes a transition from one zoom level to another, as the result of either user interaction or methods such as Map#flyTo.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just after a zoom transition finishes.
map.on('zoomend', function() {
console.log('A zoomend event occurred.');
});
rotatestart
Fired when a “drag to rotate” interaction starts. See DragRotateHandler.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just before a "drag to rotate" interaction starts.
map.on('rotatestart', function() {
console.log('A rotatestart event occurred.');
});
rotate
Fired repeatedly during a “drag to rotate” interaction. See DragRotateHandler.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during "drag to rotate" interaction.
map.on('rotate', function() {
console.log('A rotate event occurred.');
});
rotateend
Fired when a “drag to rotate” interaction ends. See DragRotateHandler.
Properties
-
data
**(MapMouseEventMapTouchEvent)**
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just after a "drag to rotate" interaction ends.
map.on('rotateend', function() {
console.log('A rotateend event occurred.');
});
pitchstart
Fired whenever the map’s pitch (tilt) begins a change as the result of either user interaction or methods such as Map#flyTo .
Properties
data
MapEventData
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just before a pitch (tilt) transition starts.
map.on('pitchstart', function() {
console.log('A pitchstart event occurred.');
});
pitch
Fired repeatedly during the map’s pitch (tilt) animation between one state and another as the result of either user interaction or methods such as Map#flyTo.
Properties
data
MapEventData
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// repeatedly during a pitch (tilt) transition.
map.on('pitch', function() {
console.log('A pitch event occurred.');
});
pitchend
Fired immediately after the map’s pitch (tilt) finishes changing as the result of either user interaction or methods such as Map#flyTo.
Properties
data
MapEventData
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just after a pitch (tilt) transition ends.
map.on('pitchend', function() {
console.log('A pitchend event occurred.');
});
boxzoomstart
Fired when a “box zoom” interaction starts. See BoxZoomHandler.
Properties
data
MapBoxZoomEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just before a "box zoom" interaction starts.
map.on('boxzoomstart', function() {
console.log('A boxzoomstart event occurred.');
});
boxzoomend
Fired when a “box zoom” interaction ends. See BoxZoomHandler.
Type: Object
Properties
data
MapBoxZoomEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just after a "box zoom" interaction ends.
map.on('boxzoomend', function() {
console.log('A boxzoomend event occurred.');
});
boxzoomcancel
Fired when the user cancels a “box zoom” interaction, or when the bounding box does not meet the minimum size threshold. See BoxZoomHandler.
Properties
data
MapBoxZoomEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// the user cancels a "box zoom" interaction.
map.on('boxzoomcancel', function() {
console.log('A boxzoomcancel event occurred.');
});
webglcontextlost
Fired when the WebGL context is lost.
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the WebGL context is lost.
map.on('webglcontextlost', function() {
console.log('A webglcontextlost event occurred.');
});
webglcontextrestored
Fired when the WebGL context is restored.
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the WebGL context is restored.
map.on('webglcontextrestored', function() {
console.log('A webglcontextrestored event occurred.');
});
load
Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred.
Type: Object
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the map has finished loading.
map.on('load', function() {
console.log('A load event occurred.');
});
render
Fired whenever the map is drawn to the screen, as the result of
- a change to the map’s position, zoom, pitch, or bearing
- a change to the map’s style
- a change to a GeoJSON source
- the loading of a vector tile, GeoJSON file, glyph, or sprite
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// whenever the map is drawn to the screen.
map.on('render', function() {
console.log('A render event occurred.');
});
idle
Fired after the last frame rendered before the map enters an “idle” state:
- No camera transitions are in progress
- All currently requested tiles have loaded
- All fade/transition animations have completed
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// just before the map enters an "idle" state.
map.on('idle', function() {
console.log('A idle event occurred.');
});
error
Fired when an error occurs. This is GL JS’s primary error reporting
mechanism. We use an event instead of throw
to better accommodate
asyncronous operations. If no listeners are bound to the error
event, the
error will be printed to the console.
Properties
data
{error: {message: string}}
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when an error occurs.
map.on('error', function() {
console.log('A error event occurred.');
});
data
Fired when any map data loads or changes. See MapDataEvent for more information.
Properties
data
MapDataEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when map data loads or changes.
map.on('data', function() {
console.log('A data event occurred.');
});
styledata
Fired when the map’s style loads or changes. See MapDataEvent for more information.
Properties
data
MapDataEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when the map's style loads or changes.
map.on('styledata', function() {
console.log('A styledata event occurred.');
});
sourcedata
Fired when one of the map’s sources loads or changes, including if a tile belonging to a source loads or changes. See MapDataEvent for more information.
Properties
data
MapDataEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when one of the map's sources loads or changes.
map.on('sourcedata', function() {
console.log('A sourcedata event occurred.');
});
dataloading
Fired when any map data (style, source, tile, etc) begins loading or
changing asyncronously. All dataloading
events are followed by a data
or error
event. See MapDataEvent for more information.
Properties
data
MapDataEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// when any map data begins loading
// or changing asynchronously.
map.on('dataloading', function() {
console.log('A dataloading event occurred.');
});
styledataloading
Fired when the map’s style begins loading or changing asyncronously.
All styledataloading
events are followed by a styledata
or error
event. See MapDataEvent for more information.
Properties
data
MapDataEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// map's style begins loading or
// changing asyncronously.
map.on('styledataloading', function() {
console.log('A styledataloading event occurred.');
});
sourcedataloading
Fired when one of the map’s sources begins loading or changing asyncronously.
All sourcedataloading
events are followed by a sourcedata
or error
event.
See MapDataEvent for more information.
Properties
data
MapDataEvent
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// map's sources begin loading or
// changing asyncronously.
map.on('sourcedataloading', function() {
console.log('A sourcedataloading event occurred.');
});
styleimagemissing
Fired when an icon or pattern needed by the style is missing. The missing image can be added with Map#addImage within this event listener callback to prevent the image from being skipped. This event can be used to dynamically generate icons and patterns.
Properties
id
string The id of the missing image.
Examples
// Initialize the map
var map = new mapboxgl.Map({ // map options });
// Set an event listener that fires
// an icon or pattern is missing.
map.on('styleimagemissing', function() {
console.log('A styleimagemissing event occurred.');
});