Properties and options
Mapbox GL JS's global properties and options that you can access while initializing your map or accessing information about its status.
accessToken
src/index.tsGets and sets the map's access token.
stringReturns
string
: The currently set access token.
Example
mapboxgl.accessToken = myAccessToken;
Related
AnimationOptions
src/ui/camera.tsOptions 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.
ObjectProperties
(number)
: The zooming "curve" that will occur along the
flight path. A high value maximizes zooming for an exaggerated animation, while a low
value minimizes zooming for an effect closer to
Map#easeTo
. 1.42 is the average
value selected by participants in the user study discussed in
van Wijk (2003)
. A value of
Math.pow(6, 0.25)
would be equivalent to the root mean squared average velocity. A
value of 1 would produce a circular motion. If
minZoom
is specified, this option will be ignored.
(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.
(boolean)
: If
true
, then the animation is considered essential and will not be affected by
prefers-reduced-motion
.
(number)
: The animation's maximum duration, measured in milliseconds.
If duration exceeds maximum duration, it resets to 0.
(number)
: The zero-based zoom level at the peak of the flight path. If
this option is specified,
curve
will be ignored.
(PointLike)
: The target center's offset relative to real map container center at the end of animation.
(boolean)
: If
true
, it will trigger tiles loading across the animation path, but no animation will occur.
(number)
: The average speed of the animation measured in screenfuls
per second, assuming a linear timing curve. If
speed
is specified, this option is ignored.
(number)
: The average speed of the animation defined in relation to
curve
. A speed of 1.2 means that the map appears to move along the flight path
by 1.2 times
curve
screenfuls every second. A
screenful
is the map's visible span.
It does not correspond to a fixed physical distance, but varies by zoom level.
Related
baseApiUrl
src/index.tsGets and sets the map's default API URL for requesting tiles, styles, sprites, and glyphs.
stringReturns
string
: The current base API URL.
Example
mapboxgl.baseApiUrl = 'https://api.mapbox.com';
CameraOptions
src/ui/camera.tsOptions 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.
ObjectProperties
(LngLatLike)
: The location serving as the origin for a change in
zoom
,
pitch
and/or
bearing
.
This location will remain at the same screen position following the transform.
This is useful for drawing attention to a location that is not in the screen center.
center
is ignored if
around
is included.
(number)
: The desired bearing in degrees. The bearing is the compass direction that
is "up". For example,
bearing: 90
orients the map so that east is up.
(PaddingOptions)
: Dimensions in pixels applied on each side of the viewport for shifting the vanishing point.
Note that when
padding
is used with
jumpTo
,
easeTo
, and
flyTo
, it also sets the global map padding as a side effect,
affecting all subsequent camera movements until the padding is reset. To avoid this, add the
retainPadding: false
option.
(number)
: The desired pitch in degrees. The pitch is the angle towards the horizon
measured in degrees with a range between 0 and 85 degrees. For example, pitch: 0 provides the appearance
of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon.
Increasing the pitch value is often used to display 3D objects.
(boolean)
: If
false
, the value provided with the
padding
option will not be retained as the global map padding. This is
true
by default.
Example
// set the map's initial perspective with CameraOptions
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-73.5804, 45.53483],
pitch: 60,
bearing: -60,
zoom: 10
});
Related
clearPrewarmedResources
src/index.tsClears up resources that have previously been created by mapboxgl.prewarm()
.
Note that this is typically not necessary. You should only call this function
if you expect the user of your app to not return to a Map view at any point
in your application.
Example
mapboxgl.clearPrewarmedResources();
clearStorage
src/index.tsClears browser storage used by this library. Using this method flushes the Mapbox tile cache that is managed by this library. Tiles may still be cached by the browser in some cases.
This API is supported on browsers where the Cache
API
is supported and enabled. This includes all major browsers when pages are served over
https://
, except Internet Explorer and Edge Mobile.
When called in unsupported browsers or environments (private or incognito mode), the callback will be called with an error argument.
Parameters
Example
mapboxgl.clearStorage();
CustomLayerInterface
src/style/style_layer/custom_style_layer.tsInterface 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
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', () => {
map.addLayer(new NullIslandLayer());
});
Instance Members
Related
FreeCameraOptions
src/ui/free_camera.tsOptions for accessing physical properties of the underlying camera entity. Direct access to these properties allows more flexible and precise controlling of the camera. These options are also fully compatible and interchangeable with CameraOptions. All fields are optional. See Map#setFreeCameraOptions and Map#getFreeCameraOptions.
Parameters
(MercatorCoordinate)
Position of the camera in slightly modified web mercator coordinates.
- The size of 1 unit is the width of the projected world instead of the "mercator meter". Coordinate [0, 0, 0] is the north-west corner and [1, 1, 0] is the south-east corner.
- Z coordinate is conformal and must respect minimum and maximum zoom values.
- Zoom is automatically computed from the altitude (z).
(quat)
Orientation of the camera represented as a unit quaternion [x, y, z, w] in a left-handed coordinate space.
Direction of the rotation is clockwise around the respective axis.
The default pose of the camera is such that the forward vector is looking up the -Z axis.
The up vector is aligned with north orientation of the map:
forward: [0, 0, -1]
up: [0, -1, 0]
right [1, 0, 0]
Orientation can be set freely but certain constraints still apply:
- Orientation must be representable with only pitch and bearing.
- Pitch has an upper limit
Example
const camera = map.getFreeCameraOptions();
const position = [138.72649, 35.33974];
const altitude = 3000;
camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
camera.lookAtPoint([138.73036, 35.36197]);
map.setFreeCameraOptions(camera);
Instance Members
Related
getRTLTextPluginStatus
src/index.tsGets the map's RTL text plugin status.
The status can be unavailable
(not requested or removed), loading
, loaded
, or error
.
If the status is loaded
and the plugin is requested again, an error will be thrown.
Example
const pluginStatus = mapboxgl.getRTLTextPluginStatus();
maxParallelImageRequests
src/index.tsGets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel. 16 by default. There is no maximum value, but the number of images affects performance in raster-heavy maps.
stringReturns
number
: Number of parallel requests currently configured.
Example
mapboxgl.maxParallelImageRequests = 10;
PaddingOptions
src/ui/camera.tsOptions for setting padding on calls to methods such as Map#jumpTo, Map#easeTo, Map#flyTo,
Map#fitBounds, Map#fitScreenCoordinates, and Map#setPadding. Adjust these options to set
the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual
values for each edge. All properties of this object must be non-negative integers. Note that when padding
is used with
fitBounds
, flyTo
, or similar methods, it also sets the global map padding as a side effect, affecting all
subsequent camera movements until the padding is reset.
Properties
Example
const bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
padding: {top: 10, bottom: 25, left: 15, right: 5}
});
const bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
padding: 20
});
Related
prewarm
src/index.tsInitializes resources like WebWorkers that can be shared across maps to lower load
times in some situations. mapboxgl.workerUrl
and mapboxgl.workerCount
, if being
used, must be set before prewarm()
is called to have an effect.
By default, the lifecycle of these resources is managed automatically, and they are
lazily initialized when a Map
is first created. Invoking prewarm()
creates these
resources ahead of time and ensures they are not cleared when the last Map
is removed from the page. This allows them to be re-used by new Map
instances that
are created later. They can be manually cleared by calling
mapboxgl.clearPrewarmedResources()
.
This is only necessary if your web page remains active but stops using maps altogether.
prewarm()
is idempotent and has guards against being executed multiple times,
and any resources allocated by prewarm()
are created synchronously.
This is primarily useful when using Mapbox GL JS maps in a single page app,
in which a user navigates between various views, resulting in
constant creation and destruction of Map
instances.
Example
mapboxgl.prewarm();
RequestParameters
src/util/ajax.tsA RequestParameters
object to be returned from Map.options.transformRequest callbacks.
Properties
(boolean)
: If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.
(string)
: 'same-origin'|'include'
Use 'include' to send cookies with cross-origin requests.
(string)
: A string representing the request's referrerPolicy. For more information and possible values, see the
Referrer-Policy HTTP header page
.
Example
// use transformRequest to modify requests that begin with `http://myHost`
const map = new Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
transformRequest: (url, resourceType) => {
if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {
return {
url: url.replace('http', 'https'),
headers: {'my-custom-header': true},
credentials: 'include' // Include cookies for cross-origin requests
};
}
}
});
setRTLTextPlugin
src/index.tsSets 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
(Function)
Called with an error argument if there is an error, or no arguments if the plugin loads successfully.
(boolean)
If set to
true
, MapboxGL will defer loading the plugin until right-to-left text is encountered, and
right-to-left text will be rendered only after the plugin finishes loading.
Example
mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.0/mapbox-gl-rtl-text.js');
Related
StyleImageInterface
src/style/style_image.tsInterface 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
((Uint8Array | Uint8ClampedArray))
: Byte array representing the image. To ensure space for all four channels in an RGBA color, size must be width × height × 4.
Example
const flashingSquare = {
width: 64,
height: 64,
data: new Uint8Array(64 * 64 * 4),
onAdd(map) {
this.map = map;
},
render() {
// keep repainting while the icon is on the map
this.map.triggerRepaint();
// alternate between black and white based on the time
const value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0;
// check if image needs to be changed
if (value !== this.previousValue) {
this.previousValue = value;
const bytesPerPixel = 4;
for (let x = 0; x < this.width; x++) {
for (let y = 0; y < this.height; y++) {
const 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
Related
supported
src/index.tsTest whether the browser supports Mapbox GL JS.
Parameters
(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 (for example, a software WebGL renderer
would be used).
|
Returns
boolean
: Example
// Show an alert if the browser does not support Mapbox GL
if (!mapboxgl.supported()) {
alert('Your browser does not support Mapbox GL');
}
Related
version
src/index.tsGets the version of Mapbox GL JS in use as specified in package.json
,
CHANGELOG.md
, and the GitHub release.
Example
console.log(`Mapbox GL JS v${mapboxgl.version}`);
workerClass
src/index.tsProvides an interface for external module bundlers such as Webpack or Rollup to package mapbox-gl's WebWorker into a separate class and integrate it with the library.
Takes precedence over mapboxgl.workerUrl
.
Returns
(Object | null)
: A class that implements the
Worker
interface.
Example
import mapboxgl from 'mapbox-gl/dist/mapbox-gl-csp';
import MapboxGLWorker from 'mapbox-gl/dist/mapbox-gl-csp-worker';
mapboxgl.workerClass = MapboxGLWorker;
workerCount
src/index.tsGets and sets the number of web workers instantiated on a page with Mapbox GL JS maps. By default, it is set to 2. Make sure to set this property before creating any map instances for it to have effect.
stringReturns
number
: Number of workers currently configured.
Example
mapboxgl.workerCount = 4;
workerUrl
src/index.tsProvides an interface for loading mapbox-gl's WebWorker bundle from a self-hosted URL.
This needs to be set only once, and before any call to new mapboxgl.Map(..)
takes place.
This is useful if your site needs to operate in a strict CSP (Content Security Policy) environment
wherein you are not allowed to load JavaScript code from a Blob
URL, which is default behavior.
See our documentation on CSP Directives for more details.
stringReturns
string
: A URL hosting a JavaScript bundle for mapbox-gl's WebWorker.
Example
<script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl-csp.js'></script>
<script>
mapboxgl.workerUrl = "https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl-csp-worker.js";
...
</script>