Map (options)

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.

parameter type description
options Object
options.container (HTMLElement | string) The HTML element in which Mapbox GL JS will render the map, or the element's string id . The specified element must have no children.
options.minZoom number (default 0) The minimum zoom level of the map (0-24).
options.maxZoom number (default 22) The maximum zoom level of the map (0-24).
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 form mapbox://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-v10
  • mapbox://styles/mapbox/outdoors-v10
  • mapbox://styles/mapbox/light-v9
  • mapbox://styles/mapbox/dark-v9
  • mapbox://styles/mapbox/satellite-v9
  • mapbox://styles/mapbox/satellite-streets-v10
  • mapbox://styles/mapbox/navigation-preview-day-v2
  • mapbox://styles/mapbox/navigation-preview-night-v2
  • mapbox://styles/mapbox/navigation-guidance-day-v2
  • mapbox://styles/mapbox/navigation-guidance-night-v2

Tilesets hosted with Mapbox can be style-optimized if you append ?optimize=true to the end of your style URL, like mapbox://styles/mapbox/streets-v9?optimize=true. Learn more about style-optimized vector tiles in our API documentation.

options.hash boolean (default false) If true , 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 .
options.interactive boolean (default true) If false , no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.
options.bearingSnap number (default 7) The threshold, measured in degrees, that determines when the map's bearing will snap to north. For example, with a bearingSnap of 7, if the user rotates the map within 7 degrees of north, the map will automatically snap to exact north.
options.pitchWithRotate boolean (default true) If false , the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.
options.clickTolerance number (default 3) 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).
options.attributionControl boolean (default true) If true , an AttributionControl will be added to the map.
options.customAttribution (string | Array<string>)? String or strings to show in an AttributionControl . Only applicable if options.attributionControl is true .
options.logoPosition string (default 'bottom-left') A string representing the position of the Mapbox wordmark on the map. Valid options are top-left , top-right , bottom-left , bottom-right .
options.failIfMajorPerformanceCaveat boolean (default false) If true , 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).
options.preserveDrawingBuffer boolean (default false) If true , the map's canvas can be exported to a PNG using map.getCanvas().toDataURL() . This is false by default as a performance optimization.
options.antialias boolean? If true , the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is false by default as a performance optimization.
options.refreshExpiredTiles boolean (default true) If false , the map won't attempt to re-request tiles once they expire per their HTTP cacheControl / expires headers.
options.maxBounds LngLatBoundsLike? If set, the map will be constrained to the given bounds.
options.scrollZoom (boolean | Object) (default true) If true , the "scroll to zoom" interaction is enabled. An Object value is passed as options to ScrollZoomHandler#enable .
options.boxZoom boolean (default true) If true , the "box zoom" interaction is enabled (see BoxZoomHandler ).
options.dragRotate boolean (default true) If true , the "drag to rotate" interaction is enabled (see DragRotateHandler ).
options.dragPan boolean (default true) If true , the "drag to pan" interaction is enabled (see DragPanHandler ).
options.keyboard boolean (default true) If true , keyboard shortcuts are enabled (see KeyboardHandler ).
options.doubleClickZoom boolean (default true) If true , the "double click to zoom" interaction is enabled (see DoubleClickZoomHandler ).
options.touchZoomRotate (boolean | Object) (default true) If true , the "pinch to rotate and zoom" interaction is enabled. An Object value is passed as options to TouchZoomRotateHandler#enable .
options.trackResize boolean (default true) If true , the map will automatically resize when the browser window resizes.
options.center LngLatLike (default [0,0]) The inital geographical centerpoint of the map. If center 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.
options.zoom number (default 0) The initial zoom level of the map. If zoom 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 .
options.bearing number (default 0) The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If bearing 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 .
options.pitch number (default 0) The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). If pitch 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 .
options.bounds LngLatBoundsLike? The initial bounds of the map. If bounds is specified, it overrides center and zoom constructor options.
options.fitBoundsOptions Object? A fitBounds options object to use only when fitting the initial bounds provided above.
options.renderWorldCopies boolean (default true) If true , multiple copies of the world will be rendered, when zoomed out.
options.maxTileCacheSize number (default null) 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.
options.localIdeographFontFamily string (default 'sans-serif') Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs' 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 to false , to enable font settings from the map's style for these glyph ranges. The purpose of this option is to avoid bandwidth-intensive glyph server requests. (see Use locally generated ideographs )
options.transformRequest RequestTransformFunction (default null) 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 a url property and optionally headers and credentials properties.
options.collectResourceTiming boolean (default false) If true , 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 a resourceTiming property of relevant data events.
options.fadeDuration number (default 300) 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.
options.crossSourceCollisions boolean (default true) If true , symbols from multiple sources can collide with each other during collision detection. If false , collision detection is run separately for the symbols in each source.

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
     }
    }
  }
});

Instance Members

scrollZoom ()

The map's ScrollZoomHandler, which implements zooming in and out with a scroll wheel or trackpad.

Type: ScrollZoomHandler

boxZoom ()

The map's BoxZoomHandler, which implements zooming using a drag gesture with the Shift key pressed.

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.

Type: DragRotateHandler

dragPan ()

The map's DragPanHandler, which implements dragging the map with a mouse or touch gesture.

Type: DragPanHandler

keyboard ()

The map's KeyboardHandler, which allows the user to zoom, rotate, and pan the map using keyboard shortcuts.

Type: KeyboardHandler

doubleClickZoom ()

The map's DoubleClickZoomHandler, which allows the user to zoom by double clicking.

Type: DoubleClickZoomHandler

touchZoomRotate ()

The map's TouchZoomRotateHandler, which allows the user to zoom or rotate the map with touch gestures.

Type: TouchZoomRotateHandler

addControl (control, position?)

Adds a IControl to the map, calling control.onAdd(this).

parameter type description
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' .

Returns

Map : this

removeControl (control)

Removes the control from the map.

parameter type description
control IControl The IControl to remove.

Returns

Map : this

resize (eventData)

Resizes the map according to the dimensions of its container element.

This method must be called after the map's container is resized by another script, or when the map is shown after being initially hidden with CSS.

parameter type description
eventData Object Additional properties to be added to event objects of events triggered by this method.

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.

Returns

LngLatBounds

getMaxBounds ()

Returns the maximum geographical bounds the map is constrained to, or null if none set.

Returns

(LngLatBounds | null)

setMaxBounds (bounds)

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.

parameter type description
bounds (LngLatBoundsLike | null | undefined) The maximum bounds to set. If null or undefined is provided, the function removes the map's maximum bounds.

Returns

Map : this

setMinZoom (minZoom)

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.

parameter type description
minZoom (number | null | undefined) The minimum zoom level to set (0-24). If null or undefined is provided, the function removes the current minimum zoom (i.e. sets it to 0).

Returns

Map : this

getMinZoom ()

Returns the map's minimum allowable zoom level.

Returns

number : minZoom

setMaxZoom (maxZoom)

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.

parameter type description
maxZoom (number | null | undefined) The maximum zoom level to set. If null or undefined is provided, the function removes the current maximum zoom (sets it to 22).

Returns

Map : this

getRenderWorldCopies ()

Returns the state of renderWorldCopies.

Returns

boolean : renderWorldCopies

setRenderWorldCopies (renderWorldCopies)

Sets the state of renderWorldCopies.

parameter type description
renderWorldCopies boolean If true , multiple copies of the world will be rendered, when zoomed out. undefined is treated as true , null is treated as false .

Returns

Map : this

getMaxZoom ()

Returns the map's maximum allowable zoom level.

Returns

number : maxZoom

project (lnglat)

Returns a Point representing pixel coordinates, relative to the map's container, that correspond to the specified geographical location.

parameter type description
lnglat LngLatLike The geographical location to project.

Returns

Point : The Point corresponding to lnglat , relative to the map's container .

unproject (point)

Returns a LngLat representing geographical coordinates that correspond to the specified pixel coordinates.

parameter type description
point PointLike The pixel coordinates to unproject.

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.

Returns

boolean

isZooming ()

Returns true if the map is zooming due to a camera animation or user gesture.

Returns

boolean

isRotating ()

Returns true if the map is rotating due to a camera animation or user gesture.

Returns

boolean

on (type, listener)

Adds a listener for events of a specified type.

parameter type description
type string The event type to add a listen for.
listener Function The function to be called when the event is fired. The listener function is called with the data object passed to fire , extended with target and type properties.

Returns

Map : this

on (type, layerId, listener)

Adds a listener for events of a specified type occurring on features in a specified style layer.

parameter type description
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 and mouseover events are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. mouseleave and mouseout 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 a features property containing an array of the matching features.
listener Function The function to be called when the event is fired.

Returns

Map : this

off (type, listener)

Removes an event listener previously added with Map#on.

parameter type description
type string The event type previously used to install the listener.
listener Function The function previously installed as a listener.

Returns

Map : this

off (type, layerId, listener)

Removes an event listener for layer-specific events previously added with Map#on.

parameter type description
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 (geometry?, options?)

Returns an array of GeoJSON Feature objects representing visible features that satisfy the query parameters.

parameter type description
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 a options argument) is equivalent to passing a bounding box encompassing the entire map viewport.
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 (default true) 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.

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.

Features from layers whose visibility property is "none", or from layers whose zoom range excludes the current zoom level are not included. Symbol features that have been hidden due to text or icon collision are not included. 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.

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'] });

querySourceFeatures (sourceId, parameters?)

Returns an array of GeoJSON Feature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.

parameter type description
sourceId string The ID of the vector tile or GeoJSON source to query.
parameters Object?
parameters.sourceLayer string? The name of the vector tile 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 (default true) 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.

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 (style, options?)

Updates the map's Mapbox style object with a new value. If a style already is set and options.diff is true, this compares the style against the map's current state and performs only the changes necessary to make the map style match the desired state.

parameter type description
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.diff boolean (default true) If false, force a 'full' update, removing the current style and building the given one instead of attempting a diff-based update.
options.localIdeographFontFamily string (default 'sans-serif') Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs' 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 to false , to enable font settings from the map's style for these glyph ranges. Forces a full update.

Returns

Map : this

getStyle ()

Returns the map's Mapbox style object, which can be used to recreate the map's style.

Returns

Object : The map's style object.

isStyleLoaded ()

Returns a Boolean indicating whether the map's style is fully loaded.

Returns

boolean : A Boolean indicating whether the style is fully loaded.

addSource (id, source)

Adds a source to the map's style.

parameter type description
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 .

Returns

Map : this

isSourceLoaded (id)

Returns a Boolean indicating whether the source is loaded.

parameter type description
id string The ID of the source to be checked.

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.

Returns

boolean : A Boolean indicating whether all tiles are loaded.

removeSource (id)

Removes a source from the map's style.

parameter type description
id string The ID of the source to remove.

Returns

Map : this

getSource (id)

Returns the source with the specified ID in the map's style.

parameter type description
id string The ID of the source to get.

Returns

Object? : The style source with the specified ID, or undefined if the ID corresponds to no existing sources.

addImage (id, image, options)

Add an image to the style. This image can be used in icon-image, background-pattern, fill-pattern, and line-pattern. An Map#error event will be fired if there is not enough space in the sprite to add this image.

parameter type description
id string The ID of the image.
image (HTMLImageElement | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface) The image as an HTMLImageElement , ImageData , or object with width , height , and data properties with the same format as ImageData .
options any
options.pixelRatio any The ratio of pixels in the image to physical pixels on the screen
options.sdf any Whether the image should be interpreted as an SDF image

updateImage (id, image)

Update an existing style image. This image can be used in icon-image, background-pattern, fill-pattern, and line-pattern.

parameter type description
id string The ID of the image.
image (HTMLImageElement | ImageData | {width: number, height: number, data: (Uint8Array | Uint8ClampedArray)} | StyleImageInterface) The image as an HTMLImageElement , ImageData , or object with width , height , and data properties with the same format as ImageData .

hasImage (id)

Define whether the image has been added or not

parameter type description
id string The ID of the image.

Returns

boolean

removeImage (id)

Remove an image from the style (such as one used by icon-image or background-pattern).

parameter type description
id string The ID of the image.

loadImage (url, callback)

Load an image from an external URL for use with Map#addImage. External domains must support CORS.

parameter type description
url string The URL of the image file. Image file must be in png, webp, or jpg format.
callback Function Expecting callback(error, data) . Called when the image has loaded or with an error argument if there is an error.

listImages ()

Returns an Array of strings containing the names of all sprites/images currently available in the map

Returns

Array<string> : An Array of strings containing the names of all sprites/images currently available in the map

addLayer (layer, beforeId?)

Adds a Mapbox style layer to the map's style.

A layer defines styling for data from a specified source.

parameter type description
layer (Object | CustomLayerInterface) The style layer to add, conforming to the Mapbox Style Specification's layer definition .
beforeId string? The ID of an existing layer to insert the new layer before. If this argument is omitted, the layer will be appended to the end of the layers array.

Returns

Map : this

moveLayer (id, beforeId?)

Moves a layer to a different z-position.

parameter type description
id string The ID of the layer to move.
beforeId string? The ID of an existing layer to insert the new layer before. If this argument is omitted, the layer will be appended to the end of the layers array.

Returns

Map : this

removeLayer (id)

Removes the layer with the given id from the map's style.

If no such layer exists, an error event is fired.

parameter type description
id string id of the layer to remove

getLayer (id)

Returns the layer with the specified ID in the map's style.

parameter type description
id string The ID of the layer to get.

Returns

Object? : The layer with the specified ID, or undefined if the ID corresponds to no existing layers.

setFilter (layerId, filter, options = {})

Sets the filter for the specified style layer.

parameter type description
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 . If null or undefined is provided, the function removes any existing filter from the layer.
options Object? = {}
options.validate boolean (default true) 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.

Returns

Map : this

Examples

map.setFilter('my-layer', ['==', 'name', 'USA']);

setLayerZoomRange (layerId, minzoom, maxzoom)

Sets the zoom extent for the specified style layer.

parameter type description
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).

Returns

Map : this

Examples

map.setLayerZoomRange('my-layer', 2, 5);

getFilter (layerId)

Returns the filter applied to the specified style layer.

parameter type description
layerId string The ID of the style layer whose filter to get.

Returns

Array : The layer's filter.

setPaintProperty (layerId, name, value, options = {})

Sets the value of a paint property in the specified style layer.

parameter type description
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.validate boolean (default true) Whether to check if value 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.

Returns

Map : this

Examples

map.setPaintProperty('my-layer', 'fill-color', '#faafee');

getPaintProperty (layerId, name)

Returns the value of a paint property in the specified style layer.

parameter type description
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 (layerId, name, value, options = {})

Sets the value of a layout property in the specified style layer.

parameter type description
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.validate boolean (default true) Whether to check if value 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.

Returns

Map : this

Examples

map.setLayoutProperty('my-layer', 'visibility', 'none');

getLayoutProperty (layerId, name)

Returns the value of a layout property in the specified style layer.

parameter type description
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 (light, options = {})

Sets the any combination of light values.

parameter type description
light LightSpecification Light properties to set. Must conform to the Mapbox Style Specification .
options Object? = {}
options.validate boolean (default true) 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.

Returns

Map : this

getLight ()

Returns the value of the light object.

Returns

Object : light Light properties of the style.

setFeatureState (feature, state)

Sets the state of a feature. The state object is merged in with the existing state of the feature.

parameter type description
feature Object Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.
feature.id (string | number) Unique id of the feature.
feature.source string The Id of the vector source or GeoJSON source for the feature.
feature.sourceLayer string? (optional) For vector tile sources, the sourceLayer is required.
state Object A set of key-value pairs. The values should be valid JSON types.

This method requires the feature.id attribute on data sets. For GeoJSON sources without feature ids, set the generateIds option in the GeoJSONSourceSpecification to auto-assign them. This option assigns ids based on a feature's index in the source data. If you change feature data using map.getSource('some id').setData(..), you may need to re-apply state taking into account updated id values.

removeFeatureState (target, key)

Removes feature state, setting it back to the default behavior. If only source is specified, removes all states of that source. If target.id is also specified, removes all keys for that feature's state. If key is also specified, removes that key from that feature's state.

parameter type description
target Object Identifier of where to set state: 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.
target.id (string | number) (optional) Unique id of the feature. Optional if key is not specified.
target.source string The Id of the vector source or GeoJSON source for the feature.
target.sourceLayer string? (optional) For vector tile sources, the sourceLayer is required.
key string (optional) The key in the feature state to reset.

getFeatureState (feature)

Gets the state of a feature.

parameter type description
feature Object Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.
feature.id (string | number) Unique id of the feature.
feature.source string The Id of the vector source or GeoJSON source for the feature.
feature.sourceLayer string? (optional) For vector tile sources, the sourceLayer is required.

Returns

Object : The state of the feature.

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.

showTileBoundaries ()

Gets and sets a Boolean indicating whether the map will render an outline around each tile. These tile boundaries are useful for debugging.

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

getCenter ()

Returns the map's geographical centerpoint.

Returns

LngLat : The map's geographical centerpoint.

setCenter (center, eventData)

Sets the map's geographical centerpoint. Equivalent to jumpTo({center: center}).

parameter type description
center LngLatLike The centerpoint to set.
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

Examples

map.setCenter([-74, 38]);

panBy (offset, options, eventData)

Pans the map by the specified offset.

parameter type description
offset PointLike x and y coordinates by which to pan the map.
options AnimationOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

panTo (lnglat, options, eventData)

Pans the map to the specified location, with an animated transition.

parameter type description
lnglat LngLatLike The location to pan the map to.
options AnimationOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

getZoom ()

Returns the map's current zoom level.

Returns

number : The map's current zoom level.

setZoom (zoom, eventData)

Sets the map's zoom level. Equivalent to jumpTo({zoom: zoom}).

parameter type description
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.

Returns

Map : this

Examples

// zoom the map to 5
map.setZoom(5);

zoomTo (zoom, options, eventData)

Zooms the map to the specified zoom level, with an animated transition.

parameter type description
zoom number The zoom level to transition to.
options AnimationOptions?
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

zoomIn (options, eventData)

Increases the map's zoom level by 1.

parameter type description
options AnimationOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

zoomOut (options, eventData)

Decreases the map's zoom level by 1.

parameter type description
options AnimationOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

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 (bearing, eventData)

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}).

parameter type description
bearing number The desired bearing.
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

Examples

// rotate the map to 90 degrees
map.setBearing(90);

rotateTo (bearing, options, eventData)

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.

parameter type description
bearing number The desired bearing.
options AnimationOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

resetNorth (options, eventData)

Rotates the map so that north is up (0° bearing), with an animated transition.

parameter type description
options AnimationOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

snapToNorth (options, eventData)

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

parameter type description
options AnimationOptions
eventData 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 (pitch, eventData)

Sets the map's pitch (tilt). Equivalent to jumpTo({pitch: pitch}).

parameter type description
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 (bounds, options)

parameter type description
bounds LatLngBoundsLike Calculate the center for these bounds in the viewport and use the highest zoom level up to and including Map#getMaxZoom() that fits in the viewport. LatLngBounds represent a box that is always axis-aligned with bearing 0.
options CameraOptions
options.padding (number | PaddingOptions)? The amount of padding in pixels to add to the given bounds.
options.offset PointLike (default [0,0]) The center of the given bounds relative to the map's center, measured in pixels.
options.maxZoom number? The maximum zoom level to allow when the camera would transition to the specified bounds.

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.

Examples

var bbox = [[-79, 43], [-73, 45]];
var newCameraTransform = map.cameraForBounds(bbox, {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});

fitBounds (bounds, options?, eventData?)

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.

parameter type description
bounds LngLatBoundsLike Center these bounds in the viewport and use the highest zoom level up to and including Map#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 (number | PaddingOptions)? The amount of padding in pixels to add to the given bounds.
options.linear boolean (default false) If true , the map transitions using Map#easeTo . If false , the map transitions using Map#flyTo . See those functions and AnimationOptions for information about options available.
options.easing Function? An easing function for the animated transition. See AnimationOptions .
options.offset PointLike (default [0,0]) The center of the given bounds relative to the map's center, measured in pixels.
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.

Returns

Map : this

Examples

var bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});

fitScreenCoordinates (p0, p1, bearing, options, eventData)

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.

parameter type description
p0 PointLike First point on screen, in pixel coordinates
p1 PointLike Second point on screen, in pixel coordinates
bearing number Desired map bearing at end of animation, in degrees
options any
options.padding (number | PaddingOptions)? The amount of padding in pixels to add to the given bounds.
options.linear boolean (default false) If true , the map transitions using Map#easeTo . If false , the map transitions using Map#flyTo . See those functions and AnimationOptions for information about options available.
options.easing Function? An easing function for the animated transition. See AnimationOptions .
options.offset PointLike (default [0,0]) The center of the given bounds relative to the map's center, measured in pixels.
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.

Returns

Map : this

Examples

var p0 = [220, 400];
var p1 = [500, 900];
map.fitScreenCoordinates(p0, p1, map.getBearing(), {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});

jumpTo (options, eventData)

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.

parameter type description
options CameraOptions
eventData Object Additional properties to be added to event objects of events triggered by this method.

Returns

Map : this

easeTo (options, eventData)

Changes any combination of center, zoom, bearing, and pitch, with an animated transition between old and new values. The map will retain its current values for any details not specified in options.

parameter type description
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 (options, eventData)

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.

parameter type description
options Object Options describing the destination and animation of the transition. Accepts CameraOptions , AnimationOptions , and the following additional options.
options.curve number (default 1.42) 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 of Math.pow(6, 0.25) would be equivalent to the root mean squared average velocity. A value of 1 would produce a circular motion.
options.minZoom number? The zero-based zoom level at the peak of the flight path. If options.curve is specified, this option is ignored.
options.speed number (default 1.2) The average speed of the animation defined in relation to options.curve . A speed of 1.2 means that the map appears to move along the flight path by 1.2 times options.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.
options.screenSpeed number? The average speed of the animation measured in screenfuls per second, assuming a linear timing curve. If options.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.

Returns

Map : this

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;
  }
});

stop ()

Stops any animated transition underway.

Returns

Map : this

Events

resize ()

Fired immediately after the map has been resized.

remove ()

Fired immediately after the map has been removed with Map.event:remove.

mousedown ()

Fired when a pointing device (usually a mouse) is pressed within the map.

property type description
data MapMouseEvent

mouseup ()

Fired when a pointing device (usually a mouse) is released within the map.

property type description
data MapMouseEvent

mouseover ()

Fired when a pointing device (usually a mouse) is moved within the map.

property type description
data MapMouseEvent

mousemove ()

Fired when a pointing device (usually a mouse) is moved within the map.

property type description
data MapMouseEvent

click ()

Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.

property type description
data MapMouseEvent

dblclick ()

Fired when a pointing device (usually a mouse) is clicked twice at the same point on the map.

property type description
data MapMouseEvent

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. This event can only be listened for via the three-argument version of Map#on, where the second argument specifies the desired layer.

property type description
data MapMouseEvent

mouseleave ()

Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves the map canvas. This event can only be listened for via the three-argument version of Map#on, where the second argument specifies the desired layer.

property type description
data MapMouseEvent

mouseout ()

Fired when a point device (usually a mouse) leaves the map's canvas.

property type description
data MapMouseEvent

contextmenu ()

Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.

property type description
data MapMouseEvent

wheel ()

Fired when a wheel event occurs within the map.

property type description
data MapWheelEvent

touchstart ()

Fired when a touchstart event occurs within the map.

property type description
data MapTouchEvent

touchend ()

Fired when a touchend event occurs within the map.

property type description
data MapTouchEvent

touchmove ()

Fired when a touchmove event occurs within the map.

property type description
data MapTouchEvent

touchcancel ()

Fired when a touchcancel event occurs within the map.

property type description
data MapTouchEvent

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.

property type description
data {originalEvent: DragEvent}

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.

property type description
data (MapMouseEvent | MapTouchEvent)

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.

property type description
data {originalEvent: DragEvent}

dragstart ()

Fired when a "drag to pan" interaction starts. See DragPanHandler.

property type description
data {originalEvent: DragEvent}

drag ()

Fired repeatedly during a "drag to pan" interaction. See DragPanHandler.

property type description
data (MapMouseEvent | MapTouchEvent)

dragend ()

Fired when a "drag to pan" interaction ends. See DragPanHandler.

property type description
data {originalEvent: DragEvent}

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.

property type description
data (MapMouseEvent | MapTouchEvent)

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.

property type description
data (MapMouseEvent | MapTouchEvent)

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.

property type description
data (MapMouseEvent | MapTouchEvent)

rotatestart ()

Fired when a "drag to rotate" interaction starts. See DragRotateHandler.

property type description
data (MapMouseEvent | MapTouchEvent)

rotate ()

Fired repeatedly during a "drag to rotate" interaction. See DragRotateHandler.

property type description
data (MapMouseEvent | MapTouchEvent)

rotateend ()

Fired when a "drag to rotate" interaction ends. See DragRotateHandler.

property type description
data (MapMouseEvent | MapTouchEvent)

pitchstart ()

Fired whenever the map's pitch (tilt) begins a change as the result of either user interaction or methods such as Map#flyTo .

property type description
data MapEventData

pitch ()

Fired whenever the map's pitch (tilt) changes as. the result of either user interaction or methods such as Map#flyTo.

property type description
data MapEventData

pitchend ()

Fired immediately after the map's pitch (tilt) finishes changing as the result of either user interaction or methods such as Map#flyTo.

property type description
data MapEventData

boxzoomstart ()

Fired when a "box zoom" interaction starts. See BoxZoomHandler.

property type description
data MapBoxZoomEvent

boxzoomend ()

Fired when a "box zoom" interaction ends. See BoxZoomHandler.

Type: Object

property type description
data MapBoxZoomEvent

boxzoomcancel ()

Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. See BoxZoomHandler.

property type description
data MapBoxZoomEvent

webglcontextlost ()

Fired when the WebGL context is lost.

webglcontextrestored ()

Fired when the WebGL context is restored.

load ()

Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred.

Type: Object

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

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

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.

property type description
data {error: {message: string}}

data ()

Fired when any map data loads or changes. See MapDataEvent for more information.

property type description
data MapDataEvent

styledata ()

Fired when the map's style loads or changes. See MapDataEvent for more information.

property type description
data MapDataEvent

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.

property type description
data MapDataEvent

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.

property type description
data MapDataEvent

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.

property type description
data MapDataEvent

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.

property type description
data MapDataEvent

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.

property type description
id string : The id of the missing image.

accessToken ()

Gets and sets the map's access token.

Type: string

Examples

mapboxgl.accessToken = myAccessToken;

baseApiUrl ()

Gets and sets the map's default API URL for requesting tiles, styles, sprites, and glyphs

Type: string

Examples

mapboxgl.baseApiUrl = 'https://api.mapbox.com';

workerCount ()

Gets and sets the number of web workers instantiated on a page with GL JS maps. By default, it is set to half the number of CPU cores (capped at 6). Make sure to set this property before creating any map instances for it to have effect.

Type: string

Examples

mapboxgl.workerCount = 2;

maxParallelImageRequests ()

Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, which affects performance in raster-heavy maps. 16 by default.

Type: string

Examples

mapboxgl.maxParallelImageRequests = 10;

supported (options?)

Test whether the browser supports Mapbox GL JS.

parameter type description
options Object?
options.failIfMajorPerformanceCaveat boolean (default false) If true , the function will return false if the performance of Mapbox GL JS would be dramatically worse than expected (e.g. a software WebGL renderer would be used).

Returns

boolean :

Examples

mapboxgl.supported() // = true

version ()

The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.

Type: string

setRTLTextPlugin (pluginURL, callback)

Sets the map's RTL text plugin. Necessary for supporting languages like Arabic and Hebrew that are written right-to-left.

parameter type description
pluginURL string URL pointing to the Mapbox RTL text plugin source.
callback Function Called with an error argument if there is an error.

Examples

mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.0/mapbox-gl-rtl-text.js');

AnimationOptions ()

Options common to map movement methods that involve animation, such as Map#panBy and Map#easeTo, controlling the duration and easing function of the animation. All properties are optional.

Type: Object

property type description
duration number : The animation's duration, measured in milliseconds.
easing Function : A function taking a time in the range 0..1 and returning a number where 0 is the initial state and 1 is the final state.
offset PointLike : of the target center relative to real map container center at the end of animation.
animate boolean : If false , no animation will occur.

CameraOptions ()

Options common to Map#jumpTo, Map#easeTo, and Map#flyTo, controlling the desired location, zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current camera value for that property will remain unchanged.

Type: Object

property type description
center LngLatLike : The desired center.
zoom number : The desired zoom level.
bearing number : The desired bearing, in degrees. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.
pitch number : The desired pitch, in degrees.
around LngLatLike : If zoom is specified, around determines the point around which the zoom is centered.

PaddingOptions ()

Options for setting padding on a call to Map#fitBounds. All properties of this object must be non-negative integers.

Type: Object

property type description
top number : Padding in pixels from the top of the map canvas.
bottom number : Padding in pixels from the bottom of the map canvas.
left number : Padding in pixels from the left of the map canvas.
right number : Padding in pixels from the right of the map canvas.

RequestParameters ()

A RequestParameters object to be returned from Map.options.transformRequest callbacks.

Type: Object

property type description
url string : The URL to be requested.
headers Object : The headers to be sent with the request.
credentials string : 'same-origin'|'include' Use 'include' to send cookies with cross-origin requests.

StyleImageInterface ()

Interface for dynamically generated style images. This is a specification for implementers to model: it is not an exported method or class.

Images implementing this interface can be redrawn for every frame. They can be used to animate icons and patterns or make them respond to user input. Style images can implement a StyleImageInterface#render method. The method is called every frame and can be used to update the image.

property type description
width number
height number
data (Uint8Array | Uint8ClampedArray)

Examples

var flashingSquare = {
    width: 64,
    height: 64,
    data: new Uint8Array(64 * 64 * 4),

    onAdd: function(map) {
        this.map = map;
    },

    render: function() {
        // keep repainting while the icon is on the map
        this.map.triggerRepaint();

        // alternate between black and white based on the time
        var value = Math.round(Date.now() / 1000) % 2 === 0  ? 255 : 0;

        // check if image needs to be changed
        if (value !== this.previousValue) {
            this.previousValue = value;

            var bytesPerPixel = 4;
            for (var x = 0; x < this.width; x++) {
                for (var y = 0; y < this.height; y++) {
                    var offset = (y * this.width + x) * bytesPerPixel;
                    this.data[offset + 0] = value;
                    this.data[offset + 1] = value;
                    this.data[offset + 2] = value;
                    this.data[offset + 3] = 255;
                }
            }

            // return true to indicate that the image changed
            return true;
        }
    }
 }

 map.addImage('flashing_square', flashingSquare);

Instance Members

render ()

This method is called once before every frame where the icon will be used. The method can optionally update the image's data member with a new image.

If the method updates the image it must return true to commit the change. If the method returns false or nothing the image is assumed to not have changed.

If updates are infrequent it maybe easier to use Map#updateImage to update the image instead of implementing this method.

Returns

boolean : true if this method updated the image. false if the image was not changed.

onAdd (map)

Optional method called when the layer has been added to the Map with Map#addImage.

parameter type description
map Map The Map this custom layer was just added to.

onRemove ()

Optional method called when the icon is removed from the map with Map#removeImage. This gives the image a chance to clean up resources and event listeners.

CustomLayerInterface ()

Interface for custom style layers. This is a specification for implementers to model: it is not an exported method or class.

Custom layers allow a user to render directly into the map's GL context using the map's camera. These layers can be added between any regular layers using Map#addLayer.

Custom layers must have a unique id and must have the type of "custom". They must implement render and may implement prerender, onAdd and onRemove. They can trigger rendering using Map#triggerRepaint and they should appropriately handle Map.event:webglcontextlost and Map.event:webglcontextrestored.

The renderingMode property controls whether the layer is treated as a "2d" or "3d" map layer. Use:

  • "renderingMode": "3d" to use the depth buffer and share it with other layers
  • "renderingMode": "2d" to add a layer with no depth. If you need to use the depth buffer for a "2d" layer you must use an offscreen framebuffer and CustomLayerInterface#prerender
property type description
id string : A unique layer id.
type string : The layer's type. Must be "custom" .
renderingMode string : Either "2d" or "3d" . Defaults to "2d" .

Examples

// Custom layer implemented as ES6 class
class NullIslandLayer {
    constructor() {
        this.id = 'null-island';
        this.type = 'custom';
        this.renderingMode = '2d';
    }

    onAdd(map, gl) {
        const vertexSource = `
        uniform mat4 u_matrix;
        void main() {
            gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);
            gl_PointSize = 20.0;
        }`;

        const fragmentSource = `
        void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }`;

        const vertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertexShader, vertexSource);
        gl.compileShader(vertexShader);
        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragmentShader, fragmentSource);
        gl.compileShader(fragmentShader);

        this.program = gl.createProgram();
        gl.attachShader(this.program, vertexShader);
        gl.attachShader(this.program, fragmentShader);
        gl.linkProgram(this.program);
    }

    render(gl, matrix) {
        gl.useProgram(this.program);
        gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix);
        gl.drawArrays(gl.POINTS, 0, 1);
    }
}

map.on('load', function() {
    map.addLayer(new NullIslandLayer());
});

Instance Members

onAdd (map, gl)

Optional method called when the layer has been added to the Map with Map#addLayer. This gives the layer a chance to initialize gl resources and register event listeners.

parameter type description
map Map The Map this custom layer was just added to.
gl WebGLRenderingContext The gl context for the map.

onRemove (map, gl)

Optional method called when the layer has been removed from the Map with Map#removeLayer. This gives the layer a chance to clean up gl resources and event listeners.

parameter type description
map Map The Map this custom layer was just added to.
gl WebGLRenderingContext The gl context for the map.

prerender (gl, matrix)

Optional method called during a render frame to allow a layer to prepare resources or render into a texture.

The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.

parameter type description
gl WebGLRenderingContext The map's gl context.
matrix Array<number> The map's camera matrix. It projects spherical mercator coordinates to gl coordinates. The mercator coordinate [0, 0] represents the top left corner of the mercator world and [1, 1] represents the bottom right corner. When the renderingMode is "3d" , the z coordinate is conformal. A box with identical x, y, and z lengths in mercator units would be rendered as a cube. MercatorCoordinate .fromLatLng can be used to project a LngLat to a mercator coordinate.

render (gl, matrix)

Called during a render frame allowing the layer to draw into the GL context.

The layer can assume blending and depth state is set to allow the layer to properly blend and clip other layers. The layer cannot make any other assumptions about the current GL state.

If the layer needs to render to a texture, it should implement the prerender method to do this and only use the render method for drawing directly into the main framebuffer.

The blend function is set to gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA). This expects colors to be provided in premultiplied alpha form where the r, g and b values are already multiplied by the a value. If you are unable to provide colors in premultiplied form you may want to change the blend function to gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA).

parameter type description
gl WebGLRenderingContext The map's gl context.
matrix Array<number> The map's camera matrix. It projects spherical mercator coordinates to gl coordinates. The spherical mercator coordinate [0, 0] represents the top left corner of the mercator world and [1, 1] represents the bottom right corner. When the renderingMode is "3d" , the z coordinate is conformal. A box with identical x, y, and z lengths in mercator units would be rendered as a cube. MercatorCoordinate .fromLatLng can be used to project a LngLat to a mercator coordinate.

Geography & Geometry

LngLat and LngLatBounds represent points and rectanges in geographic coordinates. Point represents points in screen coordinates.

LngLat (lng, lat)

A LngLat object represents a given longitude and latitude coordinate, measured in degrees.

Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.

Note that any Mapbox GL method that accepts a LngLat object as an argument or option can also accept an Array of two numbers and will perform an implicit conversion. This flexible type is documented as LngLatLike.

parameter type description
lng number Longitude, measured in degrees.
lat number Latitude, measured in degrees.

Examples

var ll = new mapboxgl.LngLat(-73.9749, 40.7736);

Static Members

convert (input)

Converts an array of two numbers or an object with lng and lat or lon and lat properties to a LngLat object.

If a LngLat object is passed in, the function returns it unchanged.

parameter type description
input LngLatLike An array of two numbers or object to convert, or a LngLat object to return.

Returns

LngLat : A new LngLat object, if a conversion occurred, or the original LngLat object.

Examples

var arr = [-73.9749, 40.7736];
var ll = mapboxgl.LngLat.convert(arr);
ll;   // = LngLat {lng: -73.9749, lat: 40.7736}

Instance Members

wrap ()

Returns a new LngLat object whose longitude is wrapped to the range (-180, 180).

Returns

LngLat : The wrapped LngLat object.

Examples

var ll = new mapboxgl.LngLat(286.0251, 40.7736);
var wrapped = ll.wrap();
wrapped.lng; // = -73.9749

toArray ()

Returns the coordinates represented as an array of two numbers.

Returns

Array<number> : The coordinates represeted as an array of longitude and latitude.

Examples

var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
ll.toArray(); // = [-73.9749, 40.7736]

toString ()

Returns the coordinates represent as a string.

Returns

string : The coordinates represented as a string of the format 'LngLat(lng, lat)' .

Examples

var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
ll.toString(); // = "LngLat(-73.9749, 40.7736)"

toBounds (radius)

Returns a LngLatBounds from the coordinates extended by a given radius.

parameter type description
radius number = 0 Distance in meters from the coordinates to extend the bounds.

Returns

LngLatBounds : A new LngLatBounds object representing the coordinates extended by the radius .

Examples

var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
ll.toBounds(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]

LngLatLike ()

A LngLat object, an array of two numbers representing longitude and latitude, or an object with lng and lat or lon and lat properties.

Type: (LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number])

Examples

var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 37.772537];
var v3 = {lon: -122.420679, lat: 37.772537};

LngLatBounds (sw?, ne?)

A LngLatBounds object represents a geographical bounding box, defined by its southwest and northeast points in longitude and latitude.

If no arguments are provided to the constructor, a null bounding box is created.

Note that any Mapbox GL method that accepts a LngLatBounds object as an argument or option can also accept an Array of two LngLatLike constructs and will perform an implicit conversion. This flexible type is documented as LngLatBoundsLike.

parameter type description
sw LngLatLike? The southwest corner of the bounding box.
ne LngLatLike? The northeast corner of the bounding box.

Examples

var sw = new mapboxgl.LngLat(-73.9876, 40.7661);
var ne = new mapboxgl.LngLat(-73.9397, 40.8002);
var llb = new mapboxgl.LngLatBounds(sw, ne);

Static Members

convert (input)

Converts an array to a LngLatBounds object.

If a LngLatBounds object is passed in, the function returns it unchanged.

Internally, the function calls LngLat#convert to convert arrays to LngLat values.

parameter type description
input LngLatBoundsLike An array of two coordinates to convert, or a LngLatBounds object to return.

Returns

LngLatBounds : A new LngLatBounds object, if a conversion occurred, or the original LngLatBounds object.

Examples

var arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
var llb = mapboxgl.LngLatBounds.convert(arr);
llb;   // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}

Instance Members

setNorthEast (ne)

Set the northeast corner of the bounding box

parameter type description
ne LngLatLike

Returns

LngLatBounds : this

setSouthWest (sw)

Set the southwest corner of the bounding box

parameter type description
sw LngLatLike

Returns

LngLatBounds : this

extend (obj)

Extend the bounds to include a given LngLat or LngLatBounds.

parameter type description
obj (LngLat | LngLatBounds) object to extend to

Returns

LngLatBounds : this

getCenter ()

Returns the geographical coordinate equidistant from the bounding box's corners.

Returns

LngLat : The bounding box's center.

Examples

var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}

getSouthWest ()

Returns the southwest corner of the bounding box.

Returns

LngLat : The southwest corner of the bounding box.

getNorthEast ()

Returns the northeast corner of the bounding box.

Returns

LngLat : The northeast corner of the bounding box.

getNorthWest ()

Returns the northwest corner of the bounding box.

Returns

LngLat : The northwest corner of the bounding box.

getSouthEast ()

Returns the southeast corner of the bounding box.

Returns

LngLat : The southeast corner of the bounding box.

getWest ()

Returns the west edge of the bounding box.

Returns

number : The west edge of the bounding box.

getSouth ()

Returns the south edge of the bounding box.

Returns

number : The south edge of the bounding box.

getEast ()

Returns the east edge of the bounding box.

Returns

number : The east edge of the bounding box.

getNorth ()

Returns the north edge of the bounding box.

Returns

number : The north edge of the bounding box.

toArray ()

Returns the bounding box represented as an array.

Returns

Array<Array<number>> : The bounding box represented as an array, consisting of the southwest and northeast coordinates of the bounding represented as arrays of numbers.

Examples

var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]

toString ()

Return the bounding box represented as a string.

Returns

string : The bounding box represents as a string of the format 'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))' .

Examples

var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))"

isEmpty ()

Check if the bounding box is an empty/null-type box.

Returns

boolean : True if bounds have been defined, otherwise false.

LngLatBoundsLike ()

A LngLatBounds object, an array of LngLatLike objects in [sw, ne] order, or an array of numbers in [west, south, east, north] order.

Type: (LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number])

Examples

var v1 = new mapboxgl.LngLatBounds(
  new mapboxgl.LngLat(-73.9876, 40.7661),
  new mapboxgl.LngLat(-73.9397, 40.8002)
);
var v2 = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])
var v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];

Point ()

A Point geometry object, which has x and y properties representing screen coordinates in pixels.

Type: Object

PointLike ()

A Point or an array of two numbers representing x and y screen coordinates in pixels.

Type: (Point | Array<number>)

MercatorCoordinate (x, y, z)

A MercatorCoordinate object represents a projected three dimensional position.

MercatorCoordinate uses the web mercator projection (EPSG:3857) with slightly different units:

  • the size of 1 unit is the width of the projected world instead of the "mercator meter"
  • the origin of the coordinate space is at the north-west corner instead of the middle

For example, MercatorCoordinate(0, 0, 0) is the north-west corner of the mercator world and MercatorCoordinate(1, 1, 0) is the south-east corner. If you are familiar with vector tiles it may be helpful to think of the coordinate space as the 0/0/0 tile with an extent of 1.

The z dimension of MercatorCoordinate is conformal. A cube in the mercator coordinate space would be rendered as a cube.

parameter type description
x number The x component of the position.
y number The y component of the position.
z number = 0 The z component of the position.

Examples

var nullIsland = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);

Static Members

fromLngLat (lngLatLike, altitude)

Project a LngLat to a MercatorCoordinate.

parameter type description
lngLatLike LngLatLike The location to project.
altitude number = 0 The altitude in meters of the position.

Returns

MercatorCoordinate : The projected mercator coordinate.

Examples

var coord = mapboxgl.MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0);
coord; // MercatorCoordinate(0.5, 0.5, 0)

Instance Members

toLngLat ()

Returns the LngLat for the coordinate.

Returns

LngLat : The LngLat object.

Examples

var coord = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);
var latLng = coord.toLngLat(); // LngLat(0, 0)

toAltitude ()

Returns the altitude in meters of the coordinate.

Returns

number : The altitude in meters.

Examples

var coord = new mapboxgl.MercatorCoordinate(0, 0, 0.02);
coord.toAltitude(); // 6914.281956295339

User Interface

Controls, markers, and popups add new user interface elements to the map.

IControl ()

Interface for interactive controls added to the map. This is an specification for implementers to model: it is not an exported method or class.

Controls must implement onAdd and onRemove, and must own an element, which is often a div element. To use Mapbox GL JS's default control styling, add the mapboxgl-ctrl class to your control's node.

Examples

// Control implemented as ES6 class
class HelloWorldControl {
    onAdd(map) {
        this._map = map;
        this._container = document.createElement('div');
        this._container.className = 'mapboxgl-ctrl';
        this._container.textContent = 'Hello, world';
        return this._container;
    }

    onRemove() {
        this._container.parentNode.removeChild(this._container);
        this._map = undefined;
    }
}

// Control implemented as ES5 prototypical class
function HelloWorldControl() { }

HelloWorldControl.prototype.onAdd = function(map) {
    this._map = map;
    this._container = document.createElement('div');
    this._container.className = 'mapboxgl-ctrl';
    this._container.textContent = 'Hello, world';
    return this._container;
};

HelloWorldControl.prototype.onRemove = function () {
     this._container.parentNode.removeChild(this._container);
     this._map = undefined;
};

Instance Members

onAdd (map)

Register a control on the map and give it a chance to register event listeners and resources. This method is called by Map#addControl internally.

parameter type description
map Map the Map this control will be added to

Returns

HTMLElement : The control's container element. This should be created by the control and returned by onAdd without being attached to the DOM: the map will insert the control's element into the DOM as necessary.

onRemove (map)

Unregister a control on the map and give it a chance to detach event listeners and resources. This method is called by Map#removeControl internally.

parameter type description
map Map the Map this control will be removed from

Returns

undefined : there is no required return value for this method

getDefaultPosition ()

Optionally provide a default position for this control. If this method is implemented and Map#addControl is called without the position parameter, the value returned by getDefaultPosition will be used as the control's position.

Returns

string : a control position, one of the values valid in addControl.

GeolocateControl (options?)

A GeolocateControl control provides a button that uses the browser's geolocation API to locate the user on the map.

Not all browsers support geolocation, and some users may disable the feature. Geolocation support for modern browsers including Chrome requires sites to be served over HTTPS. If geolocation support is not available, the GeolocateControl will not be visible.

The zoom level applied will depend on the accuracy of the geolocation provided by the device.

The GeolocateControl has two modes. If trackUserLocation is false (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If trackUserLocation is true the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three states:

  • active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center.
  • passive - the user's location dot automatically updates, but the map's camera does not.
  • disabled
parameter type description
options Object?
options.positionOptions Object (default {enableHighAccuracy:false,timeout:6000}) A Geolocation API PositionOptions object.
options.fitBoundsOptions Object (default {maxZoom:15}) A fitBounds options object to use when the map is panned and zoomed to the user's location. The default is to use a maxZoom of 15 to limit how far the map will zoom in for very accurate locations.
options.trackUserLocation Object (default false) If true the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes.
options.showUserLocation Object (default true) By default a dot will be shown on the map at the user's location. Set to false to disable.

Examples

map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true
    },
    trackUserLocation: true
}));

Instance Members

trigger ()

Trigger a geolocation

Returns

boolean : Returns false if called before control was added to a map, otherwise returns true .

Events

geolocate ()

Fired on each Geolocation API position update which returned as success.

property type description
data Position : The returned Position object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition() .

error ()

Fired on each Geolocation API position update which returned as an error.

property type description
data PositionError : The returned PositionError object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition() .

trackuserlocationstart ()

Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes).

trackuserlocationend ()

Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not.

AttributionControl (options = {})

An AttributionControl control presents the map's attribution information.

parameter type description
options Object? = {}
options.compact boolean? If true force a compact attribution that shows the full attribution on mouse hover, or if false force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide.
options.customAttribution (string | Array<string>)? String or strings to show in addition to any other attributions.

Examples

var map = new mapboxgl.Map({attributionControl: false})
    .addControl(new mapboxgl.AttributionControl({
        compact: true
    }));

ScaleControl (options?)

A ScaleControl control displays the ratio of a distance on the map to the corresponding distance on the ground.

parameter type description
options Object?
options.maxWidth number (default '100') The maximum length of the scale control in pixels.
options.unit string (default 'metric') Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).

Examples

var scale = new mapboxgl.ScaleControl({
    maxWidth: 80,
    unit: 'imperial'
});
map.addControl(scale);

scale.setUnit('metric');

Instance Members

setUnit (unit)

Set the scale's unit of the distance

parameter type description
unit Unit Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).

FullscreenControl (options?)

A FullscreenControl control contains a button for toggling the map in and out of fullscreen mode.

parameter type description
options Object?
options.container HTMLElement? container is the compatible DOM element which should be made full screen. By default, the map container element will be made full screen.

Examples

map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));

Marker (options?, legacyOptions)

Creates a marker component

parameter type description
options Object?
options.element HTMLElement? DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.
options.anchor string (default 'center') A string indicating the part of the Marker that should be positioned closest to the coordinate set via Marker#setLngLat . Options are 'center' , 'top' , 'bottom' , 'left' , 'right' , 'top-left' , 'top-right' , 'bottom-left' , and 'bottom-right' .
options.offset PointLike? The offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.
options.color string (default '#3FB1CE') The color to use for the default marker if options.element is not provided. The default is light blue.
options.draggable boolean (default false) A boolean indicating whether or not a marker is able to be dragged to a new position on the map.
legacyOptions Options

Examples

var marker = new mapboxgl.Marker()
  .setLngLat([30.5, 50.5])
  .addTo(map);

Instance Members

addTo (map)

Attaches the marker to a map

parameter type description
map Map

Returns

Marker : this

remove ()

Removes the marker from a map

Returns

Marker : this

Examples

var marker = new mapboxgl.Marker().addTo(map);
marker.remove();

getLngLat ()

Get the marker's geographical location.

The longitude of the result may differ by a multiple of 360 degrees from the longitude previously set by setLngLat because Marker wraps the anchor longitude across copies of the world to keep the marker on screen.

Returns

LngLat :

setLngLat (lnglat)

Set the marker's geographical position and move it.

parameter type description
lnglat LngLatLike

Returns

Marker : this

getElement ()

Returns the Marker's HTML element.

Returns

HTMLElement : element

setPopup (popup)

Binds a Popup to the Marker

parameter type description
popup Popup? an instance of the Popup class. If undefined or null, any popup set on this Marker instance is unset

Returns

Marker : this

getPopup ()

Returns the Popup instance that is bound to the Marker

Returns

Popup : popup

togglePopup ()

Opens or closes the bound popup, depending on the current state

Returns

Marker : this

getOffset ()

Get the marker's offset.

Returns

Point :

setOffset (offset)

Sets the offset of the marker

parameter type description
offset PointLike The offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.

Returns

Marker : this

setDraggable (shouldBeDraggable)

Sets the draggable property and functionality of the marker

parameter type description
shouldBeDraggable boolean = false Turns drag functionality on/off

Returns

Marker : this

isDraggable ()

Returns true if the marker can be dragged

Returns

boolean :

Events

dragstart ()

Fired when dragging starts

Type: Object

property type description
marker Marker : object that is being dragged

drag ()

Fired while dragging

Type: Object

property type description
marker Marker : object that is being dragged

dragend ()

Fired when the marker is finished being dragged

Type: Object

property type description
marker Marker : object that was dragged

User Interaction Handlers

Handlers add different kinds of interactivity to the map - mouse interactivity, touch interactions, and other gestures.

BoxZoomHandler (map, options)

The BoxZoomHandler allows the user to zoom the map to fit within a bounding box. The bounding box is defined by clicking and holding shift while dragging the cursor.

parameter type description
map Map
options {clickTolerance: number?}

Instance Members

isEnabled ()

Returns a Boolean indicating whether the "box zoom" interaction is enabled.

Returns

boolean : true if the "box zoom" interaction is enabled.

isActive ()

Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used.

Returns

boolean : true if the "box zoom" interaction is active.

enable ()

Enables the "box zoom" interaction.

Examples

map.boxZoom.enable();

disable ()

Disables the "box zoom" interaction.

Examples

map.boxZoom.disable();

ScrollZoomHandler (map)

The ScrollZoomHandler allows the user to zoom the map by scrolling.

parameter type description
map Map

Instance Members

setZoomRate (zoomRate)

Set the zoom rate of a trackpad

parameter type description
zoomRate number = 1/100

setWheelZoomRate (wheelZoomRate)

Set the zoom rate of a mouse wheel

parameter type description
wheelZoomRate number = 1/450

isEnabled ()

Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled.

Returns

boolean : true if the "scroll to zoom" interaction is enabled.

enable (options?)

Enables the "scroll to zoom" interaction.

parameter type description
options Object?
options.around string? If "center" is passed, map will zoom around center of map

Examples

map.scrollZoom.enable();
map.scrollZoom.enable({ around: 'center' })

disable ()

Disables the "scroll to zoom" interaction.

Examples

map.scrollZoom.disable();

DragPanHandler (map, options)

The DragPanHandler allows the user to pan the map by clicking and dragging the cursor.

parameter type description
map Map
options {clickTolerance: number?}

Instance Members

isEnabled ()

Returns a Boolean indicating whether the "drag to pan" interaction is enabled.

Returns

boolean : true if the "drag to pan" interaction is enabled.

isActive ()

Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used.

Returns

boolean : true if the "drag to pan" interaction is active.

enable ()

Enables the "drag to pan" interaction.

Examples

map.dragPan.enable();

disable ()

Disables the "drag to pan" interaction.

Examples

map.dragPan.disable();

DragRotateHandler (map, options?)

The DragRotateHandler allows the user to rotate the map by clicking and dragging the cursor while holding the right mouse button or ctrl key.

parameter type description
map Map The Mapbox GL JS map to add the handler to.
options Object?

Instance Members

isEnabled ()

Returns a Boolean indicating whether the "drag to rotate" interaction is enabled.

Returns

boolean : true if the "drag to rotate" interaction is enabled.

isActive ()

Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used.

Returns

boolean : true if the "drag to rotate" interaction is active.

enable ()

Enables the "drag to rotate" interaction.

Examples

map.dragRotate.enable();

disable ()

Disables the "drag to rotate" interaction.

Examples

map.dragRotate.disable();

KeyboardHandler (map)

The KeyboardHandler allows the user to zoom, rotate, and pan the map using the following keyboard shortcuts:

  • = / +: Increase the zoom level by 1.
  • Shift-= / Shift-+: Increase the zoom level by 2.
  • -: Decrease the zoom level by 1.
  • Shift--: Decrease the zoom level by 2.
  • Arrow keys: Pan by 100 pixels.
  • Shift+⇢: Increase the rotation by 15 degrees.
  • Shift+⇠: Decrease the rotation by 15 degrees.
  • Shift+⇡: Increase the pitch by 10 degrees.
  • Shift+⇣: Decrease the pitch by 10 degrees.
parameter type description
map Map

Instance Members

isEnabled ()

Returns a Boolean indicating whether keyboard interaction is enabled.

Returns

boolean : true if keyboard interaction is enabled.

enable ()

Enables keyboard interaction.

Examples

map.keyboard.enable();

disable ()

Disables keyboard interaction.

Examples

map.keyboard.disable();

DoubleClickZoomHandler (map)

The DoubleClickZoomHandler allows the user to zoom the map at a point by double clicking or double tapping.

parameter type description
map Map

Instance Members

isEnabled ()

Returns a Boolean indicating whether the "double click to zoom" interaction is enabled.

Returns

boolean : true if the "double click to zoom" interaction is enabled.

isActive ()

Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used.

Returns

boolean : true if the "double click to zoom" interaction is active.

enable ()

Enables the "double click to zoom" interaction.

Examples

map.doubleClickZoom.enable();

disable ()

Disables the "double click to zoom" interaction.

Examples

map.doubleClickZoom.disable();

TouchZoomRotateHandler (map)

The TouchZoomRotateHandler allows the user to zoom and rotate the map by pinching on a touchscreen.

parameter type description
map Map

Instance Members

isEnabled ()

Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled.

Returns

boolean : true if the "pinch to rotate and zoom" interaction is enabled.

enable (options?)

Enables the "pinch to rotate and zoom" interaction.

parameter type description
options Object?
options.around string? If "center" is passed, map will zoom around the center

Examples

map.touchZoomRotate.enable();
map.touchZoomRotate.enable({ around: 'center' });

disable ()

Disables the "pinch to rotate and zoom" interaction.

Examples

map.touchZoomRotate.disable();

disableRotation ()

Disables the "pinch to rotate" interaction, leaving the "pinch to zoom" interaction enabled.

Examples

map.touchZoomRotate.disableRotation();

enableRotation ()

Enables the "pinch to rotate" interaction.

Examples

map.touchZoomRotate.enable();
  map.touchZoomRotate.enableRotation();

Sources

Sources specify the geographic features to be rendered on the map. Source objects may be obtained from Map#getSource.

GeoJSONSource (id, options, dispatcher, eventedParent)

A source containing GeoJSON. (See the Style Specification for detailed documentation of options.)

parameter type description
id string
options any
dispatcher Dispatcher
eventedParent Evented

Examples

map.addSource('some id', {
    type: 'geojson',
    data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
});
map.addSource('some id', {
   type: 'geojson',
   data: {
       "type": "FeatureCollection",
       "features": [{
           "type": "Feature",
           "properties": {},
           "geometry": {
               "type": "Point",
               "coordinates": [
                   -76.53063297271729,
                   39.18174077994108
               ]
           }
       }]
   }
});
map.getSource('some id').setData({
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "properties": { "name": "Null Island" },
      "geometry": {
          "type": "Point",
          "coordinates": [ 0, 0 ]
      }
  }]
});

Instance Members

setData (data)

Sets the GeoJSON data and re-renders the map.

parameter type description
data (Object | string) A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.

Returns

GeoJSONSource : this

getClusterExpansionZoom (clusterId, callback)

For clustered sources, fetches the zoom at which the given cluster expands.

parameter type description
clusterId number The value of the cluster's cluster_id property.
callback Callback<number> A callback to be called when the zoom value is retrieved ( (error, zoom) => { ... } ).

Returns

GeoJSONSource : this

getClusterChildren (clusterId, callback)

For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).

parameter type description
clusterId number The value of the cluster's cluster_id property.
callback Callback<Array<GeoJSONFeature>> A callback to be called when the features are retrieved ( (error, features) => { ... } ).

Returns

GeoJSONSource : this

getClusterLeaves (clusterId, limit, offset, callback)

For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).

parameter type description
clusterId number The value of the cluster's cluster_id property.
limit number The maximum number of features to return.
offset number The number of features to skip (e.g. for pagination).
callback Callback<Array<GeoJSONFeature>> A callback to be called when the features are retrieved ( (error, features) => { ... } ).

Returns

GeoJSONSource : this

VideoSource (id, options, dispatcher, eventedParent)

A data source containing video. (See the Style Specification for detailed documentation of options.)

parameter type description
id string
options VideoSourceSpecification
dispatcher Dispatcher
eventedParent Evented

Examples

// add to map
map.addSource('some id', {
   type: 'video',
   url: [
       'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',
       'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'
   ],
   coordinates: [
       [-76.54, 39.18],
       [-76.52, 39.18],
       [-76.52, 39.17],
       [-76.54, 39.17]
   ]
});

// update
var mySource = map.getSource('some id');
mySource.setCoordinates([
    [-76.54335737228394, 39.18579907229748],
    [-76.52803659439087, 39.1838364847587],
    [-76.5295386314392, 39.17683392507606],
    [-76.54520273208618, 39.17876344106642]
]);

map.removeSource('some id');  // remove

Instance Members

getVideo ()

Returns the HTML video element.

Returns

HTMLVideoElement : The HTML video element.

setCoordinates (coordinates)

Sets the video's coordinates and re-renders the map.

parameter type description
coordinates Array<Array<number>> Four geographical coordinates, represented as arrays of longitude and latitude numbers, which define the corners of the video. The coordinates start at the top left corner of the video and proceed in clockwise order. They do not have to represent a rectangle.

Returns

VideoSource : this

ImageSource (id, options, dispatcher, eventedParent)

A data source containing an image. (See the Style Specification for detailed documentation of options.)

parameter type description
id string
options (ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification)
dispatcher Dispatcher
eventedParent Evented

Examples

// add to map
map.addSource('some id', {
   type: 'image',
   url: 'https://www.mapbox.com/images/foo.png',
   coordinates: [
       [-76.54, 39.18],
       [-76.52, 39.18],
       [-76.52, 39.17],
       [-76.54, 39.17]
   ]
});

// update coordinates
var mySource = map.getSource('some id');
mySource.setCoordinates([
    [-76.54335737228394, 39.18579907229748],
    [-76.52803659439087, 39.1838364847587],
    [-76.5295386314392, 39.17683392507606],
    [-76.54520273208618, 39.17876344106642]
]);

// update url and coordinates simultaneously
mySource.updateImage({
   url: 'https://www.mapbox.com/images/bar.png',
   coordinates: [
       [-76.54335737228394, 39.18579907229748],
       [-76.52803659439087, 39.1838364847587],
       [-76.5295386314392, 39.17683392507606],
       [-76.54520273208618, 39.17876344106642]
   ]
})

map.removeSource('some id');  // remove

Instance Members

updateImage (options)

Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing, set the raster-fade-duration paint property on the raster layer to 0.

parameter type description
options Object
options.url string? Required image URL.
options.coordinates Array<Array<number>>? Four geographical coordinates, represented as arrays of longitude and latitude numbers, which define the corners of the image. The coordinates start at the top left corner of the image and proceed in clockwise order. They do not have to represent a rectangle.

Returns

ImageSource : this

setCoordinates (coordinates)

Sets the image's coordinates and re-renders the map.

parameter type description
coordinates Array<Array<number>> Four geographical coordinates, represented as arrays of longitude and latitude numbers, which define the corners of the image. The coordinates start at the top left corner of the image and proceed in clockwise order. They do not have to represent a rectangle.

Returns

ImageSource : this

CanvasSource (id, options, dispatcher, eventedParent)

A data source containing the contents of an HTML canvas. See CanvasSourceOptions for detailed documentation of options.

parameter type description
id string
options CanvasSourceSpecification
dispatcher Dispatcher
eventedParent Evented

Examples

// add to map
map.addSource('some id', {
   type: 'canvas',
   canvas: 'idOfMyHTMLCanvas',
   animate: true,
   coordinates: [
       [-76.54, 39.18],
       [-76.52, 39.18],
       [-76.52, 39.17],
       [-76.54, 39.17]
   ]
});

// update
var mySource = map.getSource('some id');
mySource.setCoordinates([
    [-76.54335737228394, 39.18579907229748],
    [-76.52803659439087, 39.1838364847587],
    [-76.5295386314392, 39.17683392507606],
    [-76.54520273208618, 39.17876344106642]
]);

map.removeSource('some id');  // remove

Instance Members

play ()

Enables animation. The image will be copied from the canvas to the map on each frame.

pause ()

Disables animation. The map will display a static copy of the canvas image.

getCanvas ()

Returns the HTML canvas element.

Returns

HTMLCanvasElement : The HTML canvas element.

setCoordinates (coordinates)

Sets the canvas's coordinates and re-renders the map.

parameter type description
coordinates Array<Array<number>> Four geographical coordinates, represented as arrays of longitude and latitude numbers, which define the corners of the canvas. The coordinates start at the top left corner of the canvas and proceed in clockwise order. They do not have to represent a rectangle.

Returns

CanvasSource : this

CanvasSourceOptions ()

Options to add a canvas source type to the map.

Type: Object

property type description
type string : Source type. Must be "canvas" .
canvas (string | HTMLCanvasElement) : Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the HTMLCanvasElement itself.
coordinates Array<Array<number>> : Four geographical coordinates denoting where to place the corners of the canvas, specified in [longitude, latitude] pairs.
animate boolean? : Whether the canvas source is animated. If the canvas is static (i.e. pixels do not need to be re-read on every frame), animate should be set to false to improve performance.

Events

Map (and some other classes) emit events in response to user interactions or changes in state. Evented is the interface used to bind and unbind listeners for these events.

Evented ()

Methods mixed in to other classes for event capabilities.

Instance Members

on (type, listener)

Adds a listener to a specified event type.

parameter type description
type string The event type to add a listen for.
listener Function The function to be called when the event is fired. The listener function is called with the data object passed to fire , extended with target and type properties.

Returns

Object : this

off (type, listener)

Removes a previously registered event listener.

parameter type description
type string The event type to remove listeners for.
listener Function The listener function to remove.

Returns

Object : this

once (type, listener)

Adds a listener that will be called only once to a specified event type.

The listener will be called first time the event fires after the listener is registered.

parameter type description
type string The event type to listen for.
listener Function The function to be called when the event is fired the first time.

Returns

Object : this

MapMouseEvent (type, map, originalEvent, data)

MapMouseEvent is the event type for mouse-related map events.

parameter type description
type string
map Map
originalEvent MouseEvent
data Object = {}

Instance Members

type ()

The event type.

Type: ("mousedown" | "mouseup" | "click" | "dblclick" | "mousemove" | "mouseover" | "mouseenter" | "mouseleave" | "mouseout" | "contextmenu")

target ()

The Map object that fired the event.

Type: Map

originalEvent ()

The DOM event which caused the map event.

Type: MouseEvent

point ()

The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.

Type: Point

lngLat ()

The geographic location on the map of the mouse cursor.

Type: LngLat

preventDefault ()

Prevents subsequent default processing of the event by the map.

Calling this method will prevent the following default map behaviors:

defaultPrevented ()

true if preventDefault has been called.

Returns

boolean

MapTouchEvent (type, map, originalEvent)

MapTouchEvent is the event type for touch-related map events.

parameter type description
type string
map Map
originalEvent TouchEvent

Instance Members

type ()

The event type.

Type: ("touchstart" | "touchend" | "touchcancel")

target ()

The Map object that fired the event.

Type: Map

originalEvent ()

The DOM event which caused the map event.

Type: TouchEvent

lngLat ()

The geographic location on the map of the center of the touch event points.

Type: LngLat

point ()

The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left corner.

Type: Point

points ()

The array of pixel coordinates corresponding to a touch event's touches property.

Type: Array<Point>

lngLats ()

The geographical locations on the map corresponding to a touch event's touches property.

Type: Array<LngLat>

preventDefault ()

Prevents subsequent default processing of the event by the map.

Calling this method will prevent the following default map behaviors:

defaultPrevented ()

true if preventDefault has been called.

Returns

boolean

MapBoxZoomEvent ()

Type: Object

property type description
originalEvent MouseEvent

MapDataEvent ()

A MapDataEvent object is emitted with the Map.event:data and Map.event:dataloading events. Possible values for dataTypes are:

  • 'source': The non-tile data associated with any source
  • 'style': The style used by the map

Type: Object

property type description
type string : The event type.
dataType string : The type of data that has changed. One of 'source' , 'style' .
isSourceLoaded boolean? : True if the event has a dataType of source and the source has no outstanding network requests.
source Object? : The style spec representation of the source if the event has a dataType of source .
sourceDataType string? : Included if the event has a dataType of source and the event signals that internal data has been received or changed. Possible values are metadata and content .
tile Object? : The tile being loaded or changed, if the event has a dataType of source and the event is related to loading of a tile.
coord Coordinate? : The coordinate of the tile if the event has a dataType of source and the event is related to loading of a tile.

MapWheelEvent (type, map, originalEvent)

MapWheelEvent is the event type for the wheel map event.

parameter type description
type string
map Map
originalEvent WheelEvent

Instance Members

type ()

The event type.

Type: "wheel"

target ()

The Map object that fired the event.

Type: Map

originalEvent ()

The DOM event which caused the map event.

Type: WheelEvent

preventDefault ()

Prevents subsequent default processing of the event by the map.

Calling this method will prevent the the behavior of ScrollZoomHandler.

defaultPrevented ()

true if preventDefault has been called.

Returns

boolean