Mapbox GL JS

Current version: mapbox-gl.js v0.18.0

Mapbox GL JS is a JavaScript library that uses WebGL to render interactive maps from vector tiles and Mapbox GL 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.18.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.18.0/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-v8'
  });
</script>

Creates a map instance. This is usually the beginning of your map: you tell Mapbox GL JS where to put the map by specifying a container option, and the map's style with style and other attributes of the map, and in return Mapbox GL JS initializes the map on your page and returns a map variable that lets you programmatically call methods on the map.

new Map(options: Object)
Parameters
options (Object)
Name Description
options.container (string | Element) HTML element to initialize the map in (or element id as string)
options.minZoom [number] (default 0) Minimum zoom of the map
options.maxZoom [number] (default 20) Maximum zoom of the map
options.style [(Object | string)] Map style. This must be an an object conforming to the schema described in the style reference , or a URL to a JSON style. 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 predefined Mapbox styles .
options.hash [boolean] (default false) If true , the map will track and update the page URL according to map position
options.interactive [boolean] (default true) If false , no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input
options.bearingSnap [number] (default 7) Snap to north threshold in degrees.
options.classes [Array] Style class names with which to initialize the map
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 implementation determines that the performance of the created WebGL context would be dramatically lower than expected.
options.preserveDrawingBuffer [boolean] (default false) If true , The maps canvas can be exported to a PNG using map.getCanvas().toDataURL(); . This is false by default as a performance optimization.
options.maxBounds [(LngLatBounds | Array<Array<number>>)] If set, the map is constrained to the given bounds.
options.scrollZoom [boolean] (default true) If true , enable the "scroll to zoom" interaction (see ScrollZoomHandler )
options.boxZoom [boolean] (default true) If true , enable the "box zoom" interaction (see BoxZoomHandler )
options.dragRotate [boolean] (default true) If true , enable the "drag to rotate" interaction (see DragRotateHandler ).
options.dragPan [boolean] (default true) If true , enable the "drag to pan" interaction (see DragPanHandler ).
options.keyboard [boolean] (default true) If true , enable keyboard shortcuts (see KeyboardHandler ).
options.doubleClickZoom [boolean] (default true) If true , enable the "double click to zoom" interaction (see DoubleClickZoomHandler ).
options.touchZoomRotate [boolean] (default true) If true , enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler ).
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 (pointOrBox, params)
querySourceFeatures (sourceID, params)
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, klass)
getContainer ()
getCanvasContainer ()
getCanvas ()
loaded ()
remove ()
onError ()
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
render
contextmenu
dblclick
click
touchcancel
touchmove
touchend
touchstart
mousemove
mouseup
mousedown
moveend
move
movestart
load
zoom
zoomstart
zoomend
boxzoomstart
boxzoomend
boxzoomcancel
rotateend
rotate
rotatestart
drag
dragend
dragstart
pitch
Geography

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

Create a longitude, latitude object from a given longitude and latitude pair in degrees. Mapbox GL uses Longitude, Latitude coordinate order to match GeoJSON.

Note that any Mapbox GL method that accepts a LngLat object can also accept an Array and will perform an implicit conversion. The following lines are equivalent:

map.setCenter([-73.9749, 40.7736]);
map.setCenter( new mapboxgl.LngLat(-73.9749, 40.7736) );
new LngLat(lng: number, lat: number)
Parameters
lng (number) longitude
lat (number) latitude
Example
var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
Static Members
convert (input)
Instance Members
wrap ()
toArray ()
toString ()

Creates a bounding box from the given pair of points. If parameteres are omitted, a null bounding box is created.

new LngLatBounds(sw: LngLat, ne: LngLat)
Parameters
sw (LngLat) southwest
ne (LngLat) northeast
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.

Creates a navigation control with zoom buttons and a compass

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 , bottom-left
Example
map.addControl(new mapboxgl.Navigation({position: 'top-left'})); // position is optional

Creates a geolocation 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 , bottom-left
Example
map.addControl(new mapboxgl.Geolocate({position: 'top-left'})); // position is optional

Creates an attribution 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 , bottom-left
Example
var map = new mapboxgl.Map({attributionControl: false})
    .addControl(new mapboxgl.Attribution({position: 'top-left'}));

A base class for map-related interface elements.

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 a user to zoom the map to fit a bounding box. The bounding box is defined by holding shift while dragging the cursor.

new BoxZoomHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
isActive ()
enable ()
disable ()

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

new ScrollZoomHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
enable ()
disable ()

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

new DragPanHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
isActive ()
enable ()
disable ()

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

new DragRotateHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
isActive ()
enable ()
disable ()

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

  • = / +: increase zoom level by 1
  • Shift-= / Shift-+: increase zoom level by 2
  • -: decrease zoom level by 1
  • Shift--: decrease zoom level by 2
  • Arrow keys: pan by 80 pixels
  • Shift+⇢: increase rotation by 2 degrees
  • Shift+⇠: decrease rotation by 2 degrees
  • Shift+⇡: increase pitch by 5 degrees
  • Shift+⇣: decrease pitch by 5 degrees
new KeyboardHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
enable ()
disable ()

DoubleClickZoomHandler

js/ui/handler/dblclick_zoom.js

The DoubleClickZoomHandler allows a user to zoom the map around point by double clicking.

new DoubleClickZoomHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
enable ()
disable ()

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

new TouchZoomRotateHandler(map: )
Parameters
map ()
Instance Members
isEnabled ()
enable ()
disable ()
disableRotation ()
enableRotation ()
Sources

Adding sources to a map with these JavaScript methods lets you add content dynamically to your map after it has been loaded, or add GeoJSON content that's generated by other JavaScript. You can also add sources to your map by including them in the Mapbox GL Style that it loads.

Create a GeoJSON data source instance given an options object

new GeoJSONSource(options: [Object])
Parameters
options ([Object])
Name Description
options.data (Object | string) A GeoJSON data object or URL to it. The latter is preferable in case of large GeoJSON files.
options.maxzoom [number] (default 18) Maximum zoom to preserve detail at.
options.buffer [number] Tile buffer on each side in pixels.
options.tolerance [number] Simplification tolerance (higher means simpler) in pixels.
options.cluster [number] If the data is a collection of point features, setting this to true clusters the points by radius into groups.
options.clusterRadius [number] (default 50) Radius of each cluster when clustering points, in pixels.
options.clusterMaxZoom [number] Max zoom to cluster points on. Defaults to one zoom less than maxzoom (so that last zoom features are not clustered).
Example
var sourceObj = new mapboxgl.GeoJSONSource({
   data: {
       "type": "FeatureCollection",
       "features": [{
           "type": "Feature",
           "geometry": {
               "type": "Point",
               "coordinates": [
                   -76.53063297271729,
                   39.18174077994108
               ]
           }
       }]
   }
});
map.addSource('some id', sourceObj); // add
map.removeSource('some id');  // remove
Instance Members
setData (data)

Create a Video data source instance given an options object

new VideoSource(options: [Object])
Parameters
options ([Object])
Name Description
options.urls Array<string> An array of URLs to video files
options.coordinates Array Four geographical [lng, lat] coordinates in clockwise order defining the corners (starting with top left) of the video. Does not have to be a rectangle.
Example
var sourceObj = new mapboxgl.VideoSource({
   url: [
       'https://www.mapbox.com/videos/baltimore-smoke.mp4',
       'https://www.mapbox.com/videos/baltimore-smoke.webm'
   ],
   coordinates: [
       [-76.54335737228394, 39.18579907229748],
       [-76.52803659439087, 39.1838364847587],
       [-76.5295386314392, 39.17683392507606],
       [-76.54520273208618, 39.17876344106642]
   ]
});
map.addSource('some id', sourceObj); // add
map.removeSource('some id');  // remove
Instance Members
getVideo ()
setCoordinates (coordinates)

Create an Image source instance given an options object

new ImageSource(options: [Object])
Parameters
options ([Object])
Name Description
options.url string A string URL of an image file
options.coordinates Array Four geographical [lng, lat] coordinates in clockwise order defining the corners (starting with top left) of the image. Does not have to be a rectangle.
Example
var sourceObj = new mapboxgl.ImageSource({
   url: 'https://www.mapbox.com/images/foo.png',
   coordinates: [
       [-76.54335737228394, 39.18579907229748],
       [-76.52803659439087, 39.1838364847587],
       [-76.5295386314392, 39.17683392507606],
       [-76.54520273208618, 39.17876344106642]
   ]
});
map.addSource('some id', sourceObj); // add
map.removeSource('some id');  // remove
Instance Members
setCoordinates (coordinates)
Options

These are shared option types - predictable objects that can be supplied to multiple methods on the mapbox.Map object and others as function arguments.

CameraOptions

js/ui/camera.js

Options common to Map#jumpTo, Map#easeTo, and Map#flyTo, controlling the destination location, zoom level, bearing and pitch.

Properties
center (LngLat) : Map center
zoom (number) : Map zoom level
bearing (number) : Map rotation bearing in degrees counter-clockwise from north
pitch (number) : Map angle in degrees at which the camera is looking at the ground
around (LngLat) : If zooming, the zoom center (defaults to map center)

AnimationOptions

js/ui/camera.js

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

Properties
duration (number) : Number in milliseconds
easing (Function)
offset (Array) : point, origin of movement relative to map center
animate (boolean) : When set to false, no animation happens

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 the class change.

Properties
transition (boolean)
Popups

Creates a popup component

new Popup(options: Object)
Parameters
options (Object)
Name Description
options.closeButton boolean whether to show a close button in the top right corner of the popup.
options.closeOnClick boolean whether to close the popup when the map is clicked.
options.anchor string One of "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", or "bottom-right", describing where the popup's anchor relative to the coordinate set via setLngLat .
Example
var tooltip = 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

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.

When an event [fires]#Evented.fire as a result of a user interaction, the event will be called with an EventData object containing the original DOM event along with coordinates of the event target.

Properties
originalEvent (Event) : The original DOM event
point (Point) : The pixel location of the event
lngLat (LngLat) : The geographic location of the event
Example
map.on('click', function(data) {
  var e = data && data.originalEvent;
  console.log('got click ' + (e ? 'button = ' + e.button : ''));
});

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)