Mapbox GL JS

Current version: mapbox-gl.js v1.1.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.

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-24).
options.maxZoom
number
default 22
The maximum zoom level of the map (0-24).
options.style
(Object | string)?
The map's Mapbox style. This must be an a JSON object conforming to the schema described in the Mapbox Style Specification , or a URL to such JSON.

To load a style from the Mapbox API, you can use a URL of the form mapbox://styles/:owner/:style, where :owner is your Mapbox account name and :style is the style ID. Or you can use one of the following the predefined Mapbox styles:

  • mapbox://styles/mapbox/streets-v10
  • mapbox://styles/mapbox/outdoors-v10
  • mapbox://styles/mapbox/light-v9
  • mapbox://styles/mapbox/dark-v9
  • mapbox://styles/mapbox/satellite-v9
  • mapbox://styles/mapbox/satellite-streets-v10
  • mapbox://styles/mapbox/navigation-preview-day-v2
  • mapbox://styles/mapbox/navigation-preview-night-v2
  • mapbox://styles/mapbox/navigation-guidance-day-v2
  • mapbox://styles/mapbox/navigation-guidance-night-v2

Tilesets hosted with Mapbox can be style-optimized if you append ?optimize=true to the end of your style URL, like mapbox://styles/mapbox/streets-v9?optimize=true. Learn more about style-optimized vector tiles in our API documentation.

options.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 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.clickTolerance
number
default 3
The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).
options.attributionControl
boolean
default true
If true , an AttributionControl will be added to the map.
options.customAttribution
(string | Array<string>)?
String or strings to show in an AttributionControl . Only applicable if options.attributionControl is true .
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.antialias
boolean?
If true , the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. 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.bounds
LngLatBoundsLike?
The initial bounds of the map. If bounds is specified, it overrides center and zoom constructor options.
options.fitBoundsOptions
Object?
A fitBounds options object to use only when fitting the initial bounds provided above.
options.renderWorldCopies
boolean
default true
If true , multiple copies of the world will be rendered, when zoomed out.
options.maxTileCacheSize
number
default null
The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport.
options.localIdeographFontFamily
string
default 'sans-serif'
Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' 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). Set to false , to enable font settings from the map's style for these glyph ranges. 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.
options.collectResourceTiming
boolean
default false
If true , Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a resourceTiming property of relevant data events.
options.fadeDuration
number
default 300
Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.
options.crossSourceCollisions
boolean
default true
If true , symbols from multiple sources can collide with each other during collision detection. If false , collision detection is run separately for the symbols in each source.
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
Events

Gets and sets the map's access token.

Example
mapboxgl.accessToken = myAccessToken;

Gets and sets the map's default API URL for requesting tiles, styles, sprites, and glyphs

Example
mapboxgl.baseApiUrl = 'https://api.mapbox.com';

Gets and sets the number of web workers instantiated on a page with GL JS maps. By default, it is set to half the number of CPU cores (capped at 6). Make sure to set this property before creating any map instances for it to have effect.

Example
mapboxgl.workerCount = 2;

Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel, which affects performance in raster-heavy maps. 16 by default.

Example
mapboxgl.maxParallelImageRequests = 10;

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.

Sets the map's RTL text plugin. Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. Mapbox Studio loads this plugin by default.

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.2.0/mapbox-gl-rtl-text.js');

Clears browser storage used by this library. Using this method flushes the tile cache that is managed by this library. Tiles may still be cached by the browser in some cases.

Parameters
callback(Function)Called with an error argument if there is an error.

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.

Options common to Map#jumpTo, Map#easeTo, and Map#flyTo, controlling the desired location, zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current camera value for that property will remain unchanged.

Properties
center(LngLatLike): The desired center.
zoom(number): The desired zoom level.
bearing(number): The desired bearing, in degrees. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.
pitch(number): The desired pitch, in degrees.
around(LngLatLike): If zoom is specified, around determines the point around which the zoom is centered.

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

Properties
top(number): Padding in pixels from the top of the map canvas.
bottom(number): Padding in pixels from the bottom of the map canvas.
left(number): Padding in pixels from the left of the map canvas.
right(number): Padding in pixels from the right of the map canvas.

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.

Interface for dynamically generated style images. This is a specification for implementers to model: it is not an exported method or class.

Images implementing this interface can be redrawn for every frame. They can be used to animate icons and patterns or make them respond to user input. Style images can implement a StyleImageInterface#render method. The method is called every frame and can be used to update the image.

Properties
width(number)
height(number)
Example
var flashingSquare = {
    width: 64,
    height: 64,
    data: new Uint8Array(64 * 64 * 4),

    onAdd: function(map) {
        this.map = map;
    },

    render: function() {
        // keep repainting while the icon is on the map
        this.map.triggerRepaint();

        // alternate between black and white based on the time
        var value = Math.round(Date.now() / 1000) % 2 === 0  ? 255 : 0;

        // check if image needs to be changed
        if (value !== this.previousValue) {
            this.previousValue = value;

            var bytesPerPixel = 4;
            for (var x = 0; x < this.width; x++) {
                for (var y = 0; y < this.height; y++) {
                    var offset = (y * this.width + x) * bytesPerPixel;
                    this.data[offset + 0] = value;
                    this.data[offset + 1] = value;
                    this.data[offset + 2] = value;
                    this.data[offset + 3] = 255;
                }
            }

            // return true to indicate that the image changed
            return true;
        }
    }
 }

 map.addImage('flashing_square', flashingSquare);
Instance Members

Interface for custom style layers. This is a specification for implementers to model: it is not an exported method or class.

Custom layers allow a user to render directly into the map's GL context using the map's camera. These layers can be added between any regular layers using Map#addLayer.

Custom layers must have a unique id and must have the type of "custom". They must implement render and may implement prerender, onAdd and onRemove. They can trigger rendering using Map#triggerRepaint and they should appropriately handle Map.event:webglcontextlost and Map.event:webglcontextrestored.

The renderingMode property controls whether the layer is treated as a "2d" or "3d" map layer. Use:

  • "renderingMode": "3d" to use the depth buffer and share it with other layers
  • "renderingMode": "2d" to add a layer with no depth. If you need to use the depth buffer for a "2d" layer you must use an offscreen framebuffer and CustomLayerInterface#prerender
Properties
id(string): A unique layer id.
type(string): The layer's type. Must be "custom" .
renderingMode(string): Either "2d" or "3d" . Defaults to "2d" .
Example
// Custom layer implemented as ES6 class
class NullIslandLayer {
    constructor() {
        this.id = 'null-island';
        this.type = 'custom';
        this.renderingMode = '2d';
    }

    onAdd(map, gl) {
        const vertexSource = `
        uniform mat4 u_matrix;
        void main() {
            gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);
            gl_PointSize = 20.0;
        }`;

        const fragmentSource = `
        void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }`;

        const vertexShader = gl.createShader(gl.VERTEX_SHADER);
        gl.shaderSource(vertexShader, vertexSource);
        gl.compileShader(vertexShader);
        const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
        gl.shaderSource(fragmentShader, fragmentSource);
        gl.compileShader(fragmentShader);

        this.program = gl.createProgram();
        gl.attachShader(this.program, vertexShader);
        gl.attachShader(this.program, fragmentShader);
        gl.linkProgram(this.program);
    }

    render(gl, matrix) {
        gl.useProgram(this.program);
        gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix);
        gl.drawArrays(gl.POINTS, 0, 1);
    }
}

map.on('load', function() {
    map.addLayer(new NullIslandLayer());
});
Instance Members

Geography & Geometry

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

A LngLat object represents a given longitude and latitude coordinate, measured in degrees.

Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.

Note that any Mapbox GL method that accepts a LngLat object as an argument or option can also accept an Array of two numbers and will perform an implicit conversion. This flexible type is documented as LngLatLike.

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

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

Example
var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);
var v2 = [-122.420679, 37.772537];
var v3 = {lon: -122.420679, lat: 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
Instance Members

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.

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

A MercatorCoordinate object represents a projected three dimensional position.

MercatorCoordinate uses the web mercator projection (EPSG:3857) with slightly different units:

  • the size of 1 unit is the width of the projected world instead of the "mercator meter"
  • the origin of the coordinate space is at the north-west corner instead of the middle

For example, MercatorCoordinate(0, 0, 0) is the north-west corner of the mercator world and MercatorCoordinate(1, 1, 0) is the south-east corner. If you are familiar with vector tiles it may be helpful to think of the coordinate space as the 0/0/0 tile with an extent of 1.

The z dimension of MercatorCoordinate is conformal. A cube in the mercator coordinate space would be rendered as a cube.

new MercatorCoordinate(x: number, y: number, z: number)
Parameters
x(number)The x component of the position.
y(number)The y component of the position.
z(number)(default 0)The z component of the position.
Example
var nullIsland = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);
Static Members
Instance Members

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

A NavigationControl control contains zoom buttons and a compass.

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

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

Not all browsers support geolocation, and some users may disable the feature. Geolocation support for modern browsers including Chrome requires sites to be served over HTTPS. If geolocation support is not available, the GeolocateControl will not be visible.

The zoom level applied will depend on the accuracy of the geolocation provided by the device.

The GeolocateControl has two modes. If trackUserLocation is false (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If trackUserLocation is true the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three states:

  • active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center.
  • passive - the user's location dot automatically updates, but the map's camera does not.
  • disabled

Extends Evented.

new GeolocateControl(options: Object?)
Parameters
options(Object?)
NameDescription
options.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
}));
Instance Members
Events

An AttributionControl control presents the map's attribution information.

new AttributionControl(options: Object?)
Parameters
options(Object?)(default {})
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.
options.customAttribution
(string | Array<string>)?
String or strings to show in addition to any other attributions.
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 '100'
The maximum length of the scale control in pixels.
options.unit
string
default 'metric'
Unit of the distance ( 'imperial' , 'metric' or 'nautical' ).
Example
var scale = new mapboxgl.ScaleControl({
    maxWidth: 80,
    unit: 'imperial'
});
map.addControl(scale);

scale.setUnit('metric');
Instance Members

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

new FullscreenControl(options: Object?)
Parameters
options(Object?)
NameDescription
options.container
HTMLElement?
container is the compatible DOM element which should be made full screen. By default, the map container element will be made full screen.
Example
map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));

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 part of the Popup that should be positioned closest to the coordinate set via Popup#setLngLat . Options are 'center' , '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.
options.className
string?
Space-separated CSS class names to add to popup container
options.maxWidth
string
default '240px'
A string that sets the CSS property of the popup's maximum width, eg '300px' . To ensure the popup resizes to fit its content, set this property to 'none' . Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width
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, className: 'my-class'})
  .setLngLat(e.lngLat)
  .setHTML("<h1>Hello World!</h1>")
  .setMaxWidth("300px")
  .addTo(map);
Instance Members
Events

Creates a marker component

Extends Evented.

new Marker(options: Object?, legacyOptions: Options)
Parameters
options(Object?)
NameDescription
options.element
HTMLElement?
DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.
options.anchor
string
default 'center'
A string indicating the part of the Marker that should be positioned closest to the coordinate set via Marker#setLngLat . Options are 'center' , 'top' , 'bottom' , 'left' , 'right' , 'top-left' , 'top-right' , 'bottom-left' , and 'bottom-right' .
options.offset
PointLike?
The offset in pixels as a PointLike object to apply relative to the element's center. Negatives indicate left and up.
options.color
string
default '#3FB1CE'
The color to use for the default marker if options.element is not provided. The default is light blue.
options.draggable
boolean
default false
A boolean indicating whether or not a marker is able to be dragged to a new position on the map.
legacyOptions(Options)
Example
var marker = new mapboxgl.Marker()
  .setLngLat([30.5, 50.5])
  .addTo(map);
Instance Members
Events

User Interaction Handlers

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

The BoxZoomHandler allows the user to zoom the map to fit within a bounding box. The bounding box is defined by clicking and holding shift while dragging the cursor.

Instance Members

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

Instance Members

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

Instance Members

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

Instance Members

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

  • = / +: Increase the zoom level by 1.
  • Shift-= / Shift-+: Increase the zoom level by 2.
  • -: Decrease the zoom level by 1.
  • Shift--: Decrease the zoom level by 2.
  • Arrow keys: Pan by 100 pixels.
  • Shift+⇢: Increase the rotation by 15 degrees.
  • Shift+⇠: Decrease the rotation by 15 degrees.
  • Shift+⇡: Increase the pitch by 10 degrees.
  • Shift+⇣: Decrease the pitch by 10 degrees.
Instance Members

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

Instance Members

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

Instance Members

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

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
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 coordinates
var mySource = map.getSource('some id');
mySource.setCoordinates([
    [-76.54335737228394, 39.18579907229748],
    [-76.52803659439087, 39.1838364847587],
    [-76.5295386314392, 39.17683392507606],
    [-76.54520273208618, 39.17876344106642]
]);

// update url and coordinates simultaneously
mySource.updateImage({
   url: 'https://www.mapbox.com/images/bar.png',
   coordinates: [
       [-76.54335737228394, 39.18579907229748],
       [-76.52803659439087, 39.1838364847587],
       [-76.5295386314392, 39.17683392507606],
       [-76.54520273208618, 39.17876344106642]
   ]
})

map.removeSource('some id');  // remove
Instance Members
Related

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

Extends ImageSource.

Example
// add to map
map.addSource('some id', {
   type: 'canvas',
   canvas: 'idOfMyHTMLCanvas',
   animate: true,
   coordinates: [
       [-76.54, 39.18],
       [-76.52, 39.18],
       [-76.52, 39.17],
       [-76.54, 39.17]
   ]
});

// update
var mySource = map.getSource('some id');
mySource.setCoordinates([
    [-76.54335737228394, 39.18579907229748],
    [-76.52803659439087, 39.1838364847587],
    [-76.5295386314392, 39.17683392507606],
    [-76.54520273208618, 39.17876344106642]
]);

map.removeSource('some id');  // remove
Instance Members

Options to add a canvas source type to the map.

Properties
type(string): Source type. Must be "canvas" .
canvas((string | HTMLCanvasElement)): Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the HTMLCanvasElement itself.
coordinates(Array<Array<number>>): Four geographical coordinates denoting where to place the corners of the canvas, specified in [longitude, latitude] pairs.
animate(boolean?): Whether the canvas source is animated. If the canvas is static (i.e. pixels do not need to be re-read on every frame), animate should be set to false to improve performance.

Events

Map (and some other classes) emit events in response to user interactions or changes in state. Evented is the interface used to bind and unbind listeners for these events.

Methods mixed in to other classes for event capabilities.

Instance Members

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

Extends Object.

Instance Members

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

Extends Object.

Instance Members
Properties
originalEvent(MouseEvent)

A MapDataEvent object is emitted with the Map.event:data and Map.event:dataloading events. Possible values for dataTypes are:

  • 'source': The non-tile data associated with any source
  • 'style': The style used by the map
Properties
type(string): The event type.
dataType(string): The type of data that has changed. One of 'source' , 'style' .
isSourceLoaded(boolean?): True if the event has a dataType of source and the source has no outstanding network requests.
source(Object?): The style spec representation of the source if the event has a dataType of source .
sourceDataType(string?): Included if the event has a dataType of source and the event signals that internal data has been received or changed. Possible values are metadata and content .
tile(Object?): The tile being loaded or changed, if the event has a dataType of source and the event is related to loading of a tile.
coord(Coordinate?): The coordinate of the tile if the event has a dataType of source and the event is related to loading of a tile.

MapWheelEvent is the event type for the wheel map event.

Extends Object.

Instance Members