Mapbox GL JS
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.
Quickstart
Include the JavaScript and CSS files in the <head> of your HTML file.
<script src='https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.39.1/mapbox-gl.css' rel='stylesheet' />Include the following code in the <body> of your HTML file.
Install the npm package.
npm install --save mapbox-glInclude the CSS file in the <head> of your HTML file.
Include the following code in the <body> of your HTML file.
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
Map
src/ui/map.jsThe 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.
(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
. 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
Tilesets hosted with Mapbox can be style-optimized if you append |
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.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
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 ) |
var map = new mapboxgl.Map({
container: 'map',
center: [-122.420679, 37.772537],
zoom: 13,
style: style_object,
hash: true
});
accessToken
src/index.jsGets and sets the map's access token.
mapboxgl.accessToken = myAccessToken;
supported
src/index.jsTest whether the browser supports Mapbox GL JS.
boolean:
mapboxgl.supported() // = true
version
src/index.jsThe version of Mapbox GL JS in use as specified in package.json,
CHANGELOG.md, and the GitHub release.
setRTLTextPlugin
src/index.jsSets the map's RTL text plugin. Necessary for supporting languages like Arabic and Hebrew that are written right-to-left.
(string) URL pointing to the Mapbox RTL text plugin source.
(Function) Called with an error argument if there is an error.
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.jsOptions 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.
Extends Evented.
(number)
: The animation's duration, measured in milliseconds.
(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.
(PointLike)
: of the target center relative to real map container center at the end of animation.
LngLat and LngLatBounds represent points and rectanges in geographic
coordinates. Point represents points in screen coordinates.
CameraOptions
src/ui/camera.jsOptions 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.
Extends Evented.
(LngLatLike)
: The destination's center.
(number)
: The destination's zoom level.
(number)
: The destination's bearing (rotation), measured in degrees counter-clockwise from north.
(number)
: The destination's pitch (tilt), measured in degrees.
(LngLatLike)
: If a
zoom
is specified,
around
determines the zoom center (defaults to the center of the map).
LngLat
src/geo/lng_lat.jsA 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.
var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
LngLatLike
src/geo/lng_lat.jsA LngLat object, an array of two numbers representing longitude and latitude,
or an object with lng and lat properties.
var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 37.772537];
LngLatBounds
src/geo/lng_lat_bounds.jsA 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.
([LngLatLike]) The southwest corner of the bounding box.
([LngLatLike]) The northeast corner of the bounding box.
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);
LngLatBoundsLike
src/geo/lng_lat_bounds.jsA LngLatBounds object or an array of LngLatLike objects in [sw, ne] order.
var v1 = new mapboxgl.LngLatBounds(
new mapboxgl.LngLat(-73.9876, 40.7661),
new mapboxgl.LngLat(-73.9397, 40.8002)
);
var v2 = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])
var v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
Point
src/ui/map.jsA Point geometry object, which has
x and y properties representing screen coordinates in pixels.
PointLike
src/ui/map.jsA Point or an array of two numbers representing x and y screen coordinates in pixels.
Controls, markers, and popups add new user interface elements to the map.
IControl
src/ui/map.jsInterface 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.
// 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;
};
NavigationControl
src/ui/control/navigation_control.jsA NavigationControl control contains zoom buttons and a compass.
var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-left');
GeolocateControl
src/ui/control/geolocate_control.jsA 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.
([Object])
| Name | Description |
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.
|
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));
AttributionControl
src/ui/control/attribution_control.jsAn AttributionControl control presents the map's attribution information.
var map = new mapboxgl.Map({attributionControl: false})
.addControl(new mapboxgl.AttributionControl({
compact: true
}));
ScaleControl
src/ui/control/scale_control.jsA ScaleControl control displays the ratio of a distance on the map to the corresponding distance on the ground.
map.addControl(new mapboxgl.ScaleControl({
maxWidth: 80,
unit: 'imperial'
}));
FullscreenControl
src/ui/control/fullscreen_control.jsA FullscreenControl control contains a button for toggling the map in and out of fullscreen mode.
map.addControl(new mapboxgl.FullscreenControl());
Popup
src/ui/popup.jsA popup component.
Extends Evented.
([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'
. 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: |
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);
Marker
src/ui/marker.jsCreates a marker component
([HTMLElement]) DOM element to use as a marker (creates a div element by default)
var marker = new mapboxgl.Marker()
.setLngLat([30.5, 50.5])
.addTo(map);
Handlers add different kinds of interactivity to the map - mouse interactivity, touch interactions, and other gestures.
BoxZoomHandler
src/ui/handler/box_zoom.jsThe 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.
(Map) The Mapbox GL JS map to add the handler to.
ScrollZoomHandler
src/ui/handler/scroll_zoom.jsThe ScrollZoomHandler allows the user to zoom the map by scrolling.
(Map) The Mapbox GL JS map to add the handler to.
DragPanHandler
src/ui/handler/drag_pan.jsThe DragPanHandler allows the user to pan the map by clicking and dragging
the cursor.
(Map) The Mapbox GL JS map to add the handler to.
DragRotateHandler
src/ui/handler/drag_rotate.jsThe DragRotateHandler allows the user to rotate the map by clicking and
dragging the cursor while holding the right mouse button or ctrl key.
(Map) The Mapbox GL JS map to add the handler to.
KeyboardHandler
src/ui/handler/keyboard.jsThe 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.
(Map) The Mapbox GL JS map to add the handler to.
DoubleClickZoomHandler
src/ui/handler/dblclick_zoom.jsThe DoubleClickZoomHandler allows the user to zoom the map at a point by
double clicking.
(Map) The Mapbox GL JS map to add the handler to.
TouchZoomRotateHandler
src/ui/handler/touch_zoom_rotate.jsThe TouchZoomRotateHandler allows the user to zoom and rotate the map by
pinching on a touchscreen.
(Map) The Mapbox GL JS map to add the handler to.
Sources specify the geographic features to be rendered on the map. Source
objects may be obtained from Map#getSource.
GeoJSONSource
src/source/geojson_source.jsA source containing GeoJSON. (See the Style Specification for detailed documentation of options.)
Extends Evented.
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 ]
}
}]
});
VideoSource
src/source/video_source.jsA data source containing video. (See the Style Specification for detailed documentation of options.)
Extends ImageSource.
// 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
ImageSource
src/source/image_source.jsA data source containing an image. (See the Style Specification for detailed documentation of options.)
Extends Evented.
// 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
CanvasSource
src/source/canvas_source.jsA data source containing the contents of an HTML canvas. (See the Style Specification for detailed documentation of options.)
Extends ImageSource.
// 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
Evented is Mapbox GL JS's event system. It is sometimes extended when
implementing IControls and other extensions.
Evented
src/util/evented.jsMethods mixed in to other classes for event capabilities.
MapMouseEvent
src/ui/bind_handlers.js(string)
: The event type.
(MouseEvent)
(Point)
: The pixel coordinates of the mouse event target, relative to the map
and measured from the top left corner.
(LngLat)
: The geographic location on the map of the mouse event target.
MapTouchEvent
src/ui/bind_handlers.js(string)
: The event type.
(TouchEvent)
(Point)
: The pixel coordinates of the center of the touch event points, relative to the map
and measured from the top left corner.
(LngLat)
: The geographic location on the map of the center of the touch event points.
(Array<Point>)
: The array of pixel coordinates corresponding to
a
touch event's touches
property.
(Array<LngLat>)
: The geographical locations on the map corresponding to
a
touch event's touches
property.
MapBoxZoomEvent
src/ui/handler/box_zoom.js(MouseEvent)
(LngLatBounds)
: The bounding box of the "box zoom" interaction.
This property is only provided for
boxzoomend
events.
MapDataEvent
src/ui/map.jsA 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
(string)
: The event type.
([boolean])
: True if the event has a
dataType
of
source
and the source has no outstanding network requests.
([Object])
: The
style spec representation of the source
if the event has a
dataType
of
source
.
([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
.
([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.
([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.jsOptions for setting padding on a call to Map#fitBounds. All properties of this object must be non-negative integers.
Extends Evented.
workerSourceURL
src/source/source.jsAn 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).
serialize
src/source/source.jsany:
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.