Mapbox GL JS

Current version: mapbox-gl.js v0.22.1

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.

Project on Github View source code and contribute
GL JS Fundamentals Essential functions and common patterns
Gallery Project 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.
To use Mapbox GL JS with a <script> tag, include the JavaScript and CSS files in the <head> of your HTML file.
<script src='https://api.mapbox.com/mapbox-gl-js/v0.22.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.22.1/mapbox-gl.css' rel='stylesheet' />
          
Then include this code in the <body> of your HTML file to initialize a map on the page.
<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>
          

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.

The Map class mixes in Evented methods.

new Map(options: Object)
Parameters
options (Object)
Name Description
options.container (HTMLElement | string) The HTML element in which Mapbox GL JS will render the map, or the element's string id .
options.minZoom [number] (default 0) The minimum zoom level of the map (1-20).
options.maxZoom [number] (default 20) The maximum zoom level of the map (1-20).
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
options.hash [boolean] (default false) If true , the map's position (zoom, center latitude, center longitude, and bearing) 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 .
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.classes [Array<string>] Mapbox style class names with which to initialize the map. Keep in mind that these classes are used for controlling a style layer's paint properties, so are not reflected in an HTML element's class attribute. To learn more about Mapbox style classes, read about Layers in the style specification.
options.attributionControl [boolean] (default true) If true , an Attribution control will be added to the map.
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.maxBounds [LngLatBoundsLike] If set, the map will be constrained to the given bounds.
options.scrollZoom [boolean] (default true) If true , the "scroll to zoom" interaction is enabled (see ScrollZoomHandler ).
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] (default true) If true , the "pinch to rotate and zoom" interaction is enabled (see TouchZoomRotateHandler ).
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] .
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.workerCount [number] (default navigator.hardwareConcurrency-1) The number of WebWorkers that Mapbox GL JS should use to process vector tile data.
Example
var map = new mapboxgl.Map({
  container: 'map',
  center: [-122.420679, 37.772537],
  zoom: 13,
  style: style_object,
  hash: true
});
Instance Members
addControl (control)
addClass (klass, [options])
removeClass (klass, [options])
setClasses (klasses, [options])
hasClass (klass)
getClasses ()
resize ()
getBounds ()
setMaxBounds (lnglatbounds)
setMinZoom (minZoom)
setMaxZoom (maxZoom)
project (lnglat)
unproject (point)
queryRenderedFeatures ([geometry], [parameters])
querySourceFeatures (sourceID, parameters)
setStyle (style)
getStyle ()
addSource (id, source)
removeSource (id)
getSource (id)
addLayer (layer, [before])
removeLayer (id)
getLayer (id)
setFilter (layer, filter)
setLayerZoomRange (layerId, minzoom, maxzoom)
getFilter (layer)
setPaintProperty (layer, name, value, [klass])
getPaintProperty (layer, name, [klass])
setLayoutProperty (layer, name, value)
getLayoutProperty (layer, name)
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
webglcontextlost
webglcontextrestored
touchcancel
render
error
moveend
mousedown
mouseup
mousemove
touchstart
touchend
touchmove
mouseout
click
dblclick
contextmenu
load
movestart
move
zoomend
zoom
zoomstart
boxzoomend
boxzoomcancel
boxzoomstart
rotate
rotatestart
rotateend
dragend
dragstart
drag
pitch

accessToken

js/mapbox-gl.js

Gets and sets the map's access token.

Example
mapboxgl.accessToken = myAccessToken;

Returns a Boolean indicating whether the browser supports Mapbox GL JS.

Parameters
options (Object)
Name Description
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 (i.e. a software 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.

Geography

These are Mapbox GL JS's ways of representing locations and areas on the sphere.

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

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
extend (obj)
getCenter ()
getSouthWest ()
getNorthEast ()
getNorthWest ()
getSouthEast ()
getWest ()
getSouth ()
getEast ()
getNorth ()
toArray ()
toString ()
Controls

Controls add new functionality and user interface elements to the map.

A Navigation control contains zoom buttons and a compass. Extends Control.

new Navigation(options: [Object])
Parameters
options ([Object])
Name Description
options.position [string] (default 'top-right') A string indicating the control's position on the map. Options are 'top-right' , 'top-left' , 'bottom-right' , and 'bottom-left' .
Example
var nav = new mapboxgl.Navigation({position: 'top-left'}); // position is optional
map.addControl(nav);

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

new Geolocate(options: [Object])
Parameters
options ([Object])
Name Description
options.position [string] (default 'top-right') A string indicating the control's position on the map. Options are 'top-right' , 'top-left' , 'bottom-right' , and 'bottom-left' .
Example
map.addControl(new mapboxgl.Geolocate({position: 'top-left'})); // position is optional
Events
error
geolocate

An Attribution control presents the map's attribution information. Extends Control.

new Attribution(options: [Object])
Parameters
options ([Object])
Name Description
options.position [string] (default 'bottom-right') A string indicating the control's position on the map. Options are 'top-right' , 'top-left' , 'bottom-right' , and 'bottom-left' .
Example
var map = new mapboxgl.Map({attributionControl: false})
    .addControl(new mapboxgl.Attribution({position: 'top-left'}));

The base class for map-related interface elements.

The Control class mixes in Evented methods.

new Control()
Instance Members
addTo (map)
remove ()
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 ()
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])
Name Description
options.bearingSnap [number] The threshold, measured in degrees, that determines when the map's bearing (rotation) will snap to north.
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 80 pixels.
  • Shift+⇢: Increase the rotation by 2 degrees.
  • Shift+⇠: Decrease the rotation by 2 degrees.
  • Shift+⇡: Increase the pitch by 5 degrees.
  • Shift+⇣: Decrease the pitch by 5 degrees.
new KeyboardHandler(map: Map)
Parameters
map (Map) The Mapbox GL JS map to add the handler to.
Instance Members
isEnabled ()
enable ()
disable ()

DoubleClickZoomHandler

js/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 ()
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 ()
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.

new GeoJSONSource(options: [Object], id: , dispatcher: )
Parameters
options ([Object])
Name Description
options.data [(Object | string)] A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON objects.
options.maxzoom [number] (default 18) The maximum zoom level at which to preserve detail (1-20).
options.buffer [number] (default 128) The tile buffer, measured in pixels. The buffer extends each tile's data just past its visible edges, helping to ensure seamless rendering across tile boundaries. The default value, 128, is a safe value for label layers, preventing text clipping at boundaries. You can read more about buffers and clipping in the Mapbox Vector Tile Specification .
options.tolerance [number] (default 0.375) The simplification tolerance, measured in pixels. This value is passed into a modified Ramer–Douglas–Peucker algorithm to simplify (i.e. reduce the number of points) in curves. Higher values result in greater simplification.
options.cluster [boolean] If true , a collection of point features will be clustered into groups, according to options.clusterRadius .
options.clusterRadius [number] (default 50) The radius of each cluster when clustering points, measured in pixels.
options.clusterMaxZoom [number] The maximum zoom level to cluster points in. By default, this value is one zoom level less than the map's maxzoom , so that at the highest zoom level features are not clustered.
id ()
dispatcher ()
Example
map.addSource('some id', {
    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",
           "geometry": {
               "type": "Point",
               "coordinates": [
                   -76.53063297271729,
                   39.18174077994108
               ]
           }
       }]
   }
});
map.getSource('some id').setData({
    data: {
       "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.)

Example
// add to map
map.addSource('some id', {
   type: 'video',
   url: [
       'https://www.mapbox.com/videos/baltimore-smoke.mp4',
       'https://www.mapbox.com/videos/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)

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

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

These shared option can be supplied as arguments to various methods on a Map object and other functions.

CameraOptions

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

AnimationOptions

js/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) : The animation's easing function.
offset (PointLike) : x and y coordinates representing the animation's origin of movement relative to the map's center.
animate (boolean) : If false , no animation will occur.

StyleOptions

js/ui/map.js

Options common to Map#addClass, Map#removeClass, and Map#setClasses, controlling whether or not to smoothly transition property changes triggered by a class change.

Properties
transition (boolean) : If true , property changes will smootly transition.
Overlays

A popup component.

new Popup(options: [Object])
Parameters
options ([Object])
Name Description
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' .
Example
var popup = new mapboxgl.Popup()
  .setLngLat(e.lngLat)
  .setHTML("<h1>Hello World!</h1>")
  .addTo(map);
Instance Members
addTo (map)
remove ()
getLngLat ()
setLngLat (lnglat)
setText (text)
setHTML (html)
setDOMContent (htmlNode)
Events
close

Creates a marker component

new Marker(element: [HTMLElement], options: [Object])
Parameters
element ([HTMLElement]) DOM element to use as a marker (creates a div element by default)
options ([Object])
Name Description
options.offset [PointLike] The offset in pixels as a PointLike object to apply relative to the element's top left corner. 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)
Events

This event functionality is used by Mapbox GL JS itself and can be useful to other developers who want to create Controls or other extensions.

Methods mixed in to other classes for event capabilities.

Static Members
on (type, listener)
off ([type], [listener])
once (type, listener)
fire (type, [data])
listens (type)
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.
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.
Properties
originalEvent (MouseEvent)
boxZoomBounds (LngLatBounds) : The bounding box of the "box zoom" interaction. This property is only provided for boxzoomend events.
Types

These are types used in the documentation above to describe arguments, properties, and return values.

LngLatLike

js/ui/map.js

A LngLat object or an array of two numbers representing longitude and latitude.

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

LngLatBoundsLike

js/ui/map.js

A LngLatBounds object or an array of LngLatLike objects.

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

PointLike

js/ui/map.js

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