Mapbox GL JS

Current version:mapbox-gl.js v0.41.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.41.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.41.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:

child-src blob: ;
img-src data: blob: ;
script-src 'unsafe-eval' ;

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.minZoom[number](default 0)The minimum zoom level of the map (0-22).
options.maxZoom[number](default 22)The maximum zoom level of the map (0-22).
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-v9
  • mapbox://styles/mapbox/outdoors-v9
  • mapbox://styles/mapbox/light-v9
  • mapbox://styles/mapbox/dark-v9
  • mapbox://styles/mapbox/satellite-v9
  • mapbox://styles/mapbox/satellite-streets-v9

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 (rotation) 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.attributionControl[boolean](default true)If true , an AttributionControl will be added to the map.
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.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.renderWorldCopies[boolean](default true)If true , multiple copies of the world will be rendered, when zoomed out.
options.maxTileCacheSize[number](default null)The maxiumum 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 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.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.
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
addControl(control, [position])
removeControl(control)
resize()
getBounds()
getMaxBounds()
setMaxBounds(lnglatbounds)
setMinZoom(minZoom)
getMinZoom()
setMaxZoom(maxZoom)
getMaxZoom()
project(lnglat)
unproject(point)
on(type, listener)
on(type, layer, listener)
off(type, layer, listener)
off(type, listener)
queryRenderedFeatures([geometry], [parameters], args)
querySourceFeatures(sourceID, [parameters])
setStyle(style, [options])
getStyle()
isStyleLoaded()
addSource(id, source)
isSourceLoaded(id)
areTilesLoaded()
removeSource(id)
getSource(id)
addImage(id, data, options, $2)
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)
isMoving()
stop()
Events
resize
remove
mousedown
mouseup
mousemove
click
dblclick
mouseenter
mouseleave
mouseover
mouseout
contextmenu
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.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:
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.1/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.
Geography & Geometry

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

CameraOptions

src/ui/camera.js

Options common to Map#jumpTo, Map#easeTo, and Map#flyTo, controlling the destination's location, zoom level, bearing, and pitch. All properties are optional. Unspecified options will default to the map's current value for that property.

Properties
center(LngLatLike): The destination's center.
zoom(number): The destination's zoom level.
bearing(number): The destination's bearing (rotation), measured in degrees counter-clockwise from north.
pitch(number): The destination's pitch (tilt), measured in degrees.
around(LngLatLike): If a zoom is specified, around determines the zoom center (defaults to the center of the map).

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

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

A NavigationControl control contains zoom buttons and a compass.

new NavigationControl()
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.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.
Example
map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true
    },
    trackUserLocation: true
}));
Events
trackuserlocationstart
trackuserlocationend
geolocate
error

An AttributionControl control presents the map's attribution information.

new AttributionControl(options: [Object])
Parameters
options([Object])
NameDescription
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.
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.maxWidth[number](default '150')The maximum length of the scale control in pixels.
options.unit[string](default 'metric')Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).
Example
map.addControl(new mapboxgl.ScaleControl({
    maxWidth: 80,
    unit: 'imperial'
}));

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.closeButton[boolean](default true)If true , a close button will appear in the top right corner of the popup.
options.closeOnClick[boolean](default true)If true , the popup will closed when the map is clicked.
options.anchor[string]A string indicating the popup's location relative 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
close

Creates a marker component

new Marker(element: any, options: any)
Parameters
element(any)DOM element to use as a marker (creates a div element by default)
options(any)
NameDescription
options.offsetanyThe offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.
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()
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.

new BoxZoomHandler(map: Map)
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
Instance Members
isEnabled()
isActive()
enable()
disable()

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

new ScrollZoomHandler(map: Map)
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
Instance Members
isEnabled()
enable([options])
disable()

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

new DragPanHandler(map: Map)
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
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.

new DragRotateHandler(map: Map, options: [Object])
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
options([Object])
NameDescription
options.bearingSnap[number]The threshold, measured in degrees, that determines when the map's bearing (rotation) will snap to north.
options.pitchWithRotate[bool](default true)Control the map pitch in addition to the bearing
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.
new KeyboardHandler(map: Map)
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
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.

new DoubleClickZoomHandler(map: Map)
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
Instance Members
isEnabled()
isActive()
enable()
disable()

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

new TouchZoomRotateHandler(map: Map)
Parameters
map(Map)The Mapbox GL JS map to add the handler to.
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 the Style Specification 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
getCanvas()
setCoordinates(coordinates)
Events

Evented is Mapbox GL JS's event system. It is sometimes extended when implementing IControls and other extensions.

Methods mixed in to other classes for event capabilities.

Instance Members
on(type, listener)
off(type, listener)
once(type, listener)
fire(type, [data])
listens(type)

MapMouseEvent

src/ui/events.js
Properties
type(string): The event type.
target(Map): The Map object that fired the event.
originalEvent(MouseEvent)
point(Point): The pixel coordinates of the mouse event target, relative to the map and measured from the top left corner.
lngLat(LngLat): The geographic location on the map of the mouse event target.

MapTouchEvent

src/ui/events.js
Properties
type(string): The event type.
target(Map): The Map object that fired the event.
originalEvent(TouchEvent)
point(Point): The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left corner.
lngLat(LngLat): The geographic location on the map of the center of the touch event points.
points(Array<Point>): The array of pixel coordinates corresponding to a touch event's touches property.
lngLats(Array<LngLat>): The geographical locations on the map corresponding to a touch event's touches property.

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.

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.

Extends Evented.

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.

Returns null if t is a subtype of expected; otherwise returns an error message.

  • @private
Parameters
expected(Type)
t(Type)
Returns
string?

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.

workerSourceURL

src/source/source.js

An optional URL to a script which, when run by a Worker, registers a WorkerSource implementation for this Source type by calling self.registerWorkerSource(workerSource: WorkerSource).

Returns
any: A plain (stringifiable) JS object representing the current state of the source. Creating a source using the returned object as the options should result in a Source that is equivalent to this one.