Mapbox GL JS

Current version:mapbox-gl.js v0.45.0

Mapbox GL JS is a JavaScript library that uses WebGL to render interactive maps from vector tiles and Mapbox styles. It is part of the Mapbox GL ecosystem, which includes Mapbox Mobile, a compatible renderer written in C++ with bindings for desktop and mobile platforms. To see what new features our team is working on, take a look at our roadmap.

Project on GithubView source code and contribute
GL JS FundamentalsEssential functions and common patterns
GalleryProject showcase

Quickstart

To get started, you need to obtain an access token and a style URL. You can choose from one of our professionally designed styles or create your own using Mapbox Studio.

Include the JavaScript and CSS files in the <head> of your HTML file.

<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.45.0/mapbox-gl.css' rel='stylesheet' />

Include the following code in the <body> of your HTML file.

<div id='map' style='width: 400px; height: 300px;'></div>
<script>
mapboxgl.accessToken = '<your access token here>';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9'
});
</script>

CSP Directives

As a mitigation for Cross-Site Scripting and other types of web security vulnerabilities, you may use a Content Security Policy (CSP) to specify security policies for your website. If you do, Mapbox GL JS requires the following CSP directives:

worker-src blob: ;
child-src blob: ;
img-src data: blob: ;

Requesting styles from Mapbox or other services will require additional directives. For Mapbox, you can use this connect-src directive:

connect-src https://*.tiles.mapbox.com https://api.mapbox.com

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.

Extends Evented.

new Map(options: Object)
Parameters
options(Object)
NameDescription
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.minZoomnumber(default 0)The minimum zoom level of the map (0-24).
options.maxZoomnumber(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.hashboolean(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.interactiveboolean(default true)If false , no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.
options.bearingSnapnumber(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.pitchWithRotateboolean(default true)If false , the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.
options.attributionControlboolean(default true)If true , an AttributionControl will be added to the map.
options.logoPositionstring(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.failIfMajorPerformanceCaveatboolean(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.preserveDrawingBufferboolean(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.refreshExpiredTilesboolean(default true)If false , the map won't attempt to re-request tiles once they expire per their HTTP cacheControl / expires headers.
options.maxBoundsLngLatBoundsLike?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.boxZoomboolean(default true)If true , the "box zoom" interaction is enabled (see BoxZoomHandler ).
options.dragRotateboolean(default true)If true , the "drag to rotate" interaction is enabled (see DragRotateHandler ).
options.dragPanboolean(default true)If true , the "drag to pan" interaction is enabled (see DragPanHandler ).
options.keyboardboolean(default true)If true , keyboard shortcuts are enabled (see KeyboardHandler ).
options.doubleClickZoomboolean(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.trackResizeboolean(default true)If true , the map will automatically resize when the browser window resizes.
options.centerLngLatLike(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.zoomnumber(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.bearingnumber(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.pitchnumber(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.renderWorldCopiesboolean(default true)If true , multiple copies of the world will be rendered, when zoomed out.
options.maxTileCacheSizenumber(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.localIdeographFontFamilystring(default null)If specified, 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). The purpose of this option is to avoid bandwidth-intensive glyph server requests. (see Use locally generated ideographs )
options.transformRequestRequestTransformFunction(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.collectResourceTimingboolean(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.
Example
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
boxZoom
dragRotate
dragPan
keyboard
doubleClickZoom
touchZoomRotate
addControl(control, position?)
removeControl(control)
resize(eventData)
getBounds()
getMaxBounds()
setMaxBounds(lnglatbounds)
setMinZoom(minZoom)
getMinZoom()
setMaxZoom(maxZoom)
getRenderWorldCopies()
setRenderWorldCopies(renderWorldCopies)
getMaxZoom()
project(lnglat)
unproject(point)
isMoving()
isZooming()
isRotating()
on(type, listener)
on(type, layer, listener)
off(type, listener)
off(type, layer, listener)
queryRenderedFeatures(geometry?, options?)
querySourceFeatures(sourceID, parameters?)
setStyle(style, options?)
getStyle()
isStyleLoaded()
addSource(id, source)
isSourceLoaded(id)
areTilesLoaded()
removeSource(id)
getSource(id)
addImage(id, image, options)
hasImage(id)
removeImage(id)
loadImage(url, callback)
addLayer(layer, before?)
moveLayer(id, beforeId?)
removeLayer(id)
getLayer(id)
setFilter(layer, filter)
setLayerZoomRange(layerId, minzoom, maxzoom)
getFilter(layer)
setPaintProperty(layer, name, value)
getPaintProperty(layer, name)
setLayoutProperty(layer, name, value)
getLayoutProperty(layer, name)
setLight(light)
getLight()
getContainer()
getCanvasContainer()
getCanvas()
loaded()
remove()
showTileBoundaries
showCollisionBoxes
repaint
getCenter()
setCenter(center, eventData)
panBy(offset, options, eventData)
panTo(lnglat, options, eventData)
getZoom()
setZoom(zoom, eventData)
zoomTo(zoom, options, eventData)
zoomIn(options, eventData)
zoomOut(options, eventData)
getBearing()
setBearing(bearing, eventData)
rotateTo(bearing, options, eventData)
resetNorth(options, eventData)
snapToNorth(options, eventData)
getPitch()
setPitch(pitch, eventData)
fitBounds(bounds, options, eventData)
jumpTo(options, eventData)
easeTo(options, eventData)
flyTo(options, eventData)
stop()
Events
resize
remove
mousedown
mouseup
mouseover
mouseover
mousemove
click
dblclick
mouseenter
mouseleave
mouseout
contextmenu
wheel
touchstart
touchend
touchmove
touchcancel
movestart
move
moveend
dragstart
drag
dragend
zoomstart
zoom
zoomend
rotatestart
rotate
rotateend
pitchstart
pitch
pitchend
boxzoomstart
boxzoomend
boxzoomcancel
webglcontextlost
webglcontextrestored
load
render
error
data
styledata
sourcedata
dataloading
styledataloading
sourcedataloading

accessToken

src/index.js

Gets and sets the map's access token.

Example
mapboxgl.accessToken = myAccessToken;

supported

src/index.js

Test whether the browser supports Mapbox GL JS.

Parameters
options(Object?)
NameDescription
options.failIfMajorPerformanceCaveatboolean(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:
Example
mapboxgl.supported() // = true

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

setRTLTextPlugin

src/index.js

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

Parameters
pluginURL(string)URL pointing to the Mapbox RTL text plugin source.
callback(Function)Called with an error argument if there is an error.
Example
mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.2/mapbox-gl-rtl-text.js');

AnimationOptions

src/ui/camera.js

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.

Properties
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

src/ui/camera.js

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.

Properties
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

src/ui/camera.js

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

Properties
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

src/util/ajax.js

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

Properties
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.
Geography & Geometry

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

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.

new LngLat(lng: number, lat: number)
Parameters
lng(number)Longitude, measured in degrees.
lat(number)Latitude, measured in degrees.
Example
var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
Static Members
convert(input)
Instance Members
wrap()
toArray()
toString()
toBounds(radius)

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

Example
var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 37.772537];

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.

new LngLatBounds(sw: LngLatLike?, ne: LngLatLike?)
Parameters
sw(LngLatLike?)The southwest corner of the bounding box.
ne(LngLatLike?)The northeast corner of the bounding box.
Example
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)
Instance Members
setNorthEast(ne)
setSouthWest(sw)
extend(obj)
getCenter()
getSouthWest()
getNorthEast()
getNorthWest()
getSouthEast()
getWest()
getSouth()
getEast()
getNorth()
toArray()
toString()
isEmpty()

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

Example
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]];

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

PointLike

src/ui/map.js

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

User Interface

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

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.

Example
// 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
onRemove(map)
onAdd(map)
getDefaultPosition()

A NavigationControl control contains zoom buttons and a compass.

new NavigationControl(options: Object?)
Parameters
options(Object?)
NameDescription
options.showCompassBoolean(default true)If true the compass button is included.
options.showZoomBoolean(default true)If true the zoom-in and zoom-out buttons are included.
Example
var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-left');

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

Extends Evented.

new GeolocateControl(options: Object?)
Parameters
options(Object?)
NameDescription
options.positionOptionsObject(default {enableHighAccuracy:false,timeout:6000})A Geolocation API PositionOptions object.
options.fitBoundsOptionsObject(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.trackUserLocationObject(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.showUserLocationObject(default true)By default a dot will be shown on the map at the user's location. Set to false to disable.
Example
map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true
    },
    trackUserLocation: true
}));
Instance Members
trigger()
Events
geolocate
trackuserlocationend
trackuserlocationstart
error

An AttributionControl control presents the map's attribution information.

new AttributionControl(options: Object?)
Parameters
options(Object?)(default {})
NameDescription
options.compactboolean?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.
Example
var map = new mapboxgl.Map({attributionControl: false})
    .addControl(new mapboxgl.AttributionControl({
        compact: true
    }));

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

new ScaleControl(options: Object?)
Parameters
options(Object?)
NameDescription
options.maxWidthnumber(default '100')The maximum length of the scale control in pixels.
options.unitstring(default 'metric')Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).
Example
var scale = new mapboxgl.ScaleControl({
    maxWidth: 80,
    unit: 'imperial'
});
map.addControl(scale);

scale.setUnit('metric');
Instance Members
setUnit(unit)

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

new FullscreenControl()
Example
map.addControl(new mapboxgl.FullscreenControl());

A popup component.

Extends Evented.

new Popup(options: Object?)
Parameters
options(Object?)
NameDescription
options.closeButtonboolean(default true)If true , a close button will appear in the top right corner of the popup.
options.closeOnClickboolean(default true)If true , the popup will closed when the map is clicked.
options.anchorstring?A string indicating the part of the Popup that should be positioned closest to the coordinate set via Popup#setLngLat . Options are 'top' , 'bottom' , 'left' , 'right' , 'top-left' , 'top-right' , 'bottom-left' , and 'bottom-right' . If unset the anchor will be dynamically set to ensure the popup falls within the map container with a preference for 'bottom' .
options.offset(number | PointLike | Object)? A pixel offset applied to the popup's location specified as:
  • a single number specifying a distance from the popup's location
  • a PointLike specifying a constant offset
  • an object of Points specifing an offset for each anchor position Negative offsets indicate left and up.
Example
var markerHeight = 50, markerRadius = 10, linearOffset = 25;
var popupOffsets = {
 'top': [0, 0],
 'top-left': [0,0],
 'top-right': [0,0],
 'bottom': [0, -markerHeight],
 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
 'left': [markerRadius, (markerHeight - markerRadius) * -1],
 'right': [-markerRadius, (markerHeight - markerRadius) * -1]
 };
var popup = new mapboxgl.Popup({offset:popupOffsets})
  .setLngLat(e.lngLat)
  .setHTML("<h1>Hello World!</h1>")
  .addTo(map);
Instance Members
addTo(map)
isOpen()
remove()
getLngLat()
setLngLat(lnglat)
setText(text)
setHTML(html)
setDOMContent(htmlNode)
Events
open
close

Creates a marker component

new Marker(options: Options)
Parameters
options(Options)
NameDescription
options.elementanyDOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.
options.anchoranyA 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' . The default is 'center' .
options.offsetanyThe offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.
options.coloranyThe color to use for the default marker if options.element is not provided. The default is light blue.
Example
var marker = new mapboxgl.Marker()
  .setLngLat([30.5, 50.5])
  .addTo(map);
Instance Members
addTo(map)
remove()
getLngLat()
setLngLat(lnglat)
getElement()
setPopup(popup)
getPopup()
togglePopup()
getOffset()
setOffset(offset)
User Interaction Handlers

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

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.

Instance Members
isEnabled()
isActive()
enable()
disable()

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

Instance Members
isEnabled()
enable(options?)
disable()

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

Instance Members
isEnabled()
isActive()
enable()
disable()

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

Instance Members
isEnabled()
isActive()
enable()
disable()

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.
Instance Members
isEnabled()
enable()
disable()

DoubleClickZoomHandler

src/ui/handler/dblclick_zoom.js

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

Instance Members
isEnabled()
isActive()
enable()
disable()

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

Instance Members
isEnabled()
enable(options?)
disable()
disableRotation()
enableRotation()
Sources

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

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

Extends Evented.

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

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

Extends ImageSource.

Example
// 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()
setCoordinates(coordinates)
Related

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

Extends Evented.

Example
// 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
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
setCoordinates(coordinates)
Related

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

Extends ImageSource.

Example
// 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
pause()
play()
getCanvas()
setCoordinates(coordinates)

CanvasSourceOptions

src/source/canvas_source.js

Options to add a canvas source type to the map.

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

Methods mixed in to other classes for event capabilities.

Instance Members
on(type, listener)
off(type, listener)
once(type, listener)

MapMouseEvent

src/ui/events.js

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

Extends Object.

Instance Members
type
target
originalEvent
point
lngLat
preventDefault()
defaultPrevented

MapTouchEvent

src/ui/events.js

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

Extends Object.

Instance Members
type
map
originalEvent
lngLat
point
points
lngLats
preventDefault()
defaultPrevented

MapBoxZoomEvent

src/ui/events.js
Properties
originalEvent(MouseEvent)
boxZoomBounds(LngLatBounds): The bounding box of the "box zoom" interaction. This property is only provided for boxzoomend events.

MapDataEvent

src/ui/events.js

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
Properties
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

src/ui/events.js

MapWheelEvent is the event type for the wheel map event.

Extends Object.

Instance Members
type
map
originalEvent
preventDefault()
defaultPrevented