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.
Parameters
| 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
Adds a control to the map, calling control.addTo(this).
Parameters
Returns
Map:
this
addClass
(klass, options)
Adds a style class to a map.
Parameters
klass (string) name of style class
Returns
Map:
this
removeClass
(klass, options)
Removes a style class from a map.
Parameters
klass (string) name of style class
Returns
Map:
this
setClasses
(klasses, options)
Helper method to add more than one class.
Parameters
Returns
Map:
this
Check whether a style class is active.
Parameters
klass (string) Name of style class
Returns
boolean:
Return an array of the current active style classes.
Returns
boolean:
Detect the map's new width and height and resize it. Given
the container of the map specified in the Map constructor,
this reads the new width from the DOM: so this method is often
called after the map's container is resized by another script
or the map is shown after being initially hidden with CSS.
Returns
Map:
this
setMaxBounds
(lnglatbounds)
Set constraint on the map's geographical bounds. Pan or zoom operations that would result in
displaying regions that fall outside of the bounds instead result in displaying the map at the
closest point and/or zoom level of the requested operation that is within the max bounds.
Parameters
Returns
Map:
this
Set the map's minimum zoom level, and zooms map to that level if it is
currently below it. If no parameter provided, unsets the current
minimum zoom (sets it to 0)
Parameters
minZoom (number) Minimum zoom level. Must be between 0 and 20.
Returns
Map:
`this
Set the map's maximum zoom level, and zooms map to that level if it is
currently above it. If no parameter provided, unsets the current
maximum zoom (sets it to 20)
Parameters
maxZoom (number) Maximum zoom level. Must be between 0 and 20.
Returns
Map:
this
Get pixel coordinates relative to the map container, given a geographical
location.
Parameters
Returns
Object:
x
and
y
coordinates
Get geographical coordinates, given pixel coordinates.
Parameters
Returns
LngLat:
queryRenderedFeatures
(pointOrBox, params)
Query rendered features within a point or rectangle.
Parameters
pointOrBox ([(Point | Array<number> | Array<Point> | Array<Array<number>>)]) Either
[x, y]
pixel coordinates of a point, or [
[x1, y1]
,
[x2, y2]
] pixel coordinates of opposite corners of bounding rectangle. Optional: use entire viewport if omitted.
| Name |
Description |
params.layers [Array<string>]
|
Only query features from layers with these layer IDs.
|
params.filter [Array]
|
A mapbox-gl-style-spec filter.
|
Returns
Array<Object>:
features - An array of
GeoJSON
features
matching the query parameters. The GeoJSON properties of each feature are taken from
the original source. Each feature object also contains a top-level
layer
property whose value is an object representing the style layer to which the
feature belongs. Layout and paint properties in this object contain values
which are fully evaluated for the given zoom level and feature.
Example
var features = map.queryRenderedFeatures([20, 35], { layers: ['my-layer-name'] });
var features = map.queryRenderedFeatures([[10, 20], [30, 50]], { layers: ['my-layer-name'] });
querySourceFeatures
(sourceID, params)
Get data from vector tiles as an array of GeoJSON Features.
Parameters
| Name |
Description |
params.sourceLayer [string]
|
The name of the vector tile layer to get features from.
|
params.filter [Array]
|
A mapbox-gl-style-spec filter.
|
Returns
Array<Object>:
features - An array of
GeoJSON
features matching the query parameters. The GeoJSON properties of each feature are taken from the original source. Each feature object also contains a top-level
layer
property whose value is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature.
Replaces the map's style object with a new value. Unlike the style
option in the Map constructor, this method only accepts an object
of a new style, not a URL string.
Parameters
style (Object) A style object formatted as JSON
Returns
Map:
this
Get a style object that can be used to recreate the map's style.
Returns
Object:
style
Add a source to the map style.
Parameters
id (string) ID of the source. Must not be used by any existing source.
Returns
Map:
this
Remove an existing source from the map style.
Parameters
id (string) ID of the source to remove
Returns
Map:
this
Return the style source object with the given id.
Parameters
Returns
Object:
Add a layer to the map style. The layer will be inserted before the layer with
ID before, or appended if before is omitted.
Parameters
before ([string]) ID of an existing layer to insert before
Returns
Map:
this
Remove the layer with the given id from the map. Any layers which refer to the
specified layer via a ref property are also removed.
Parameters
Returns
Map:
this
Throws
- Error: if no layer with the given
id
exists
Return the style layer object with the given id.
Parameters
Returns
?Object:
a layer, if one with the given
id
exists
setFilter
(layer, filter)
Set the filter for a given style layer.
Parameters
Returns
Map:
this
Example
map.setFilter('my-layer', ['==', 'name', 'USA']);
setLayerZoomRange
(layerId, minzoom, maxzoom)
Set the zoom extent for a given style layer.
Parameters
layerId (string) ID of a layer
minzoom (number) minimum zoom extent
maxzoom (number) maximum zoom extent
Returns
Map:
this
Example
map.setLayerZoomRange('my-layer', 2, 5);
Get the filter for a given style layer.
Parameters
Returns
Array:
filter specification, as defined in the
Style Specification
setPaintProperty
(layer, name, value, klass)
Set the value of a paint property in a given style layer.
Parameters
name (string) name of a paint property
value (Any) value for the paint propery; must have the type appropriate for the property as defined in the
Style Specification
klass ([string]) optional class specifier for the property
Returns
Map:
this
Example
map.setPaintProperty('my-layer', 'fill-color', '#faafee');
getPaintProperty
(layer, name, klass)
Get the value of a paint property in a given style layer.
Parameters
name (string) name of a paint property
klass ([string]) optional class specifier for the property
Returns
Any:
value for the paint propery
setLayoutProperty
(layer, name, value)
Set the value of a layout property in a given style layer.
Parameters
name (string) name of a layout property
value (Any) value for the layout propery; must have the type appropriate for the property as defined in the
Style Specification
Returns
Map:
this
Example
map.setLayoutProperty('my-layer', 'visibility', 'none');
getLayoutProperty
(layer, name, klass)
Get the value of a layout property in a given style layer.
Parameters
name (string) name of a layout property
klass ([string]) optional class specifier for the property
Returns
Any:
value for the layout propery
Get the Map's container as an HTML element
Returns
HTMLElement:
container
Get the container for the map canvas element.
If you want to add non-GL overlays to the map, you should append them to this element. This
is the element to which event bindings for map interactivity such as panning and zooming are
attached. It will receive bubbled events for child elements such as the canvas, but not for
map controls.
Returns
HTMLElement:
container
Get the Map's canvas as an HTML canvas
Returns
HTMLElement:
canvas
Is this map fully loaded? If the style isn't loaded
or it has a change to the sources or style that isn't
propagated to its style, return false.
Returns
boolean:
whether the map is loaded
Destroys the map's underlying resources, including web workers and DOM elements. Afterwards,
you must not call any further methods on this Map instance.
Returns
undefined:
A default error handler for style.error, source.error, layer.error,
and tile.error events.
It logs the error via console.error.
Example
map.off('style.error', map.onError);
map.off('source.error', map.onError);
map.off('tile.error', map.onError);
map.off('layer.error', map.onError);
Draw an outline around each rendered tile for debugging.
Draw boxes around all symbols in the data source, showing which were
rendered and which were hidden due to collisions with other symbols for
style debugging.
Enable continuous repaint to analyze performance.
Get the current view geographical point.
Returns
LngLat:
setCenter
(center, eventData)
Sets a map location. Equivalent to jumpTo({center: center}).
Parameters
center (LngLat) Map center to jump to
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
Example
map.setCenter([-74, 38]);
panBy
(offset, options, eventData)
Pan by a certain number of pixels
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
panTo
(lnglat, options, eventData)
Pan to a certain location with easing
Parameters
lnglat (LngLat) Location to pan to
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
Get the current zoom
Returns
number:
setZoom
(zoom, eventData)
Sets a map zoom. Equivalent to jumpTo({zoom: zoom}).
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
Example
map.setZoom(5);
zoomTo
(zoom, options, eventData)
Zooms to a certain zoom level with easing.
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
zoomIn
(options, eventData)
Zoom in by 1 level
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
zoomOut
(options, eventData)
Zoom out by 1 level
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
Get the current bearing in degrees
Returns
number:
setBearing
(bearing, eventData)
Sets a map rotation. Equivalent to jumpTo({bearing: bearing}).
Parameters
bearing (number) Map rotation bearing in degrees counter-clockwise from north
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
Example
map.setBearing(90);
rotateTo
(bearing, options, eventData)
Rotate bearing by a certain number of degrees with easing
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
resetNorth
(options, eventData)
Sets map bearing to 0 (north) with easing
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
snapToNorth
(options, eventData)
Animates map bearing to 0 (north) if it's already close to it.
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
Get the current angle in degrees
Returns
number:
setPitch
(pitch, eventData)
Sets a map angle. Equivalent to jumpTo({pitch: pitch}).
Parameters
pitch (number) The angle at which the camera is looking at the ground
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
fitBounds
(bounds, options, eventData)
Zoom to contain certain geographical bounds
Parameters
| Name |
Description |
options.linear [boolean]
|
When true, the map transitions to the new camera using
#Map.easeTo
. When false, the map transitions using
#Map.flyTo
. See
#Map.flyTo
for information on options specific to that animation transition.
|
options.easing Function
|
|
options.padding number
|
how much padding there is around the given bounds on each side in pixels
|
options.maxZoom number
|
The resulting zoom level will be at most
this value.
|
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
jumpTo
(options, eventData)
Change any combination of center, zoom, bearing, and pitch, without
a transition. The map will retain the current values for any options
not included in options.
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
easeTo
(options, eventData)
Change any combination of center, zoom, bearing, and pitch, with a smooth animation
between old and new values. The map will retain the current values for any options
not included in options.
Parameters
eventData ([EventData]) Data to propagate to any event receivers
Returns
Map:
this
flyTo
(options, eventData)
Change any combination of center, zoom, bearing, and pitch, animated along a curve that
evokes flight. The transition animation seamlessly incorporates zooming and panning to help
the user find his or her bearings even after traversing a great distance.
Parameters
| Name |
Description |
options.curve [number]
(default 1.42)
|
Relative amount of zooming that takes place along the
flight path. A high value maximizes zooming for an exaggerated animation, while a low
value minimizes zooming for something closer to
#Map.easeTo
. 1.42 is the average
value selected by participants in the user study 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.
|
options.minZoom [number]
|
Zero-based zoom level at the peak of the flight path. If
options.curve
is specified, this option is ignored.
|
options.speed [number]
(default 1.2)
|
Average speed of the animation. A speed of 1.2 means that
the map appears to move along the flight path by 1.2 times
options.curve
screenfuls every
second. A
screenful
is the visible span in pixels. It does not correspond to a fixed
physical distance but rather varies by zoom level.
|
options.screenSpeed [number]
|
Average speed of the animation, measured in screenfuls
per second, assuming a linear timing curve. If
options.speed
is specified, this option
is ignored.
|
options.easing [Function]
|
Transition timing curve
|
eventData ([EventData]) Data to propagate to any event receivers
Returns
this:
Example
map.flyTo({center: [0, 0], zoom: 9});
map.flyTo({
center: [0, 0],
zoom: 9,
speed: 0.2,
curve: 1,
easing: function(t) {
return t;
}
});
Stop current animation
Returns
Map:
this
Events
WebGL Context Lost event.
Properties
originalEvent (Event)
: the original DOM event
WebGL Context Restored event.
This event is fired whenever the map is drawn to the screen because of
- a change in map position, zoom, pitch, or bearing
- a change to the map style
- a change to a GeoJSON source
- a vector tile, GeoJSON file, glyph, or sprite being loaded
Double click event.
Properties
Touch cancel event.
Properties
Touch move event.
Properties
Touch end event.
Properties
Touch start event.
Properties
Mouse move event.
Properties
Mouse up event.
Properties
Mouse down event.
Properties
Move end event. This event is emitted just after the map completes a transition from one
view to another, either as a result of user interaction or the use of methods such as Map#jumpTo.
Properties
data (EventData)
: Original event data, if fired interactively
Move event. This event is emitted repeatedly during animated transitions from one view to
another, either as a result of user interaction or the use of methods such as Map#jumpTo.
Properties
data (EventData)
: Original event data, if fired interactively
Move start event. This event is emitted just before the map begins a transition from one
view to another, either as a result of user interaction or the use of methods such as Map#jumpTo.
Properties
data (EventData)
: Original event data, if fired interactively
Load event. This event is emitted immediately after all necessary resources have been downloaded
and the first visually complete rendering has occurred.
Zoom event. This event is emitted repeatedly during animated transitions from one zoom level to
another, either as a result of user interaction or the use of methods such as Map#jumpTo.
Properties
data (EventData)
: Original event data, if fired interactively
Zoom start event. This event is emitted just before the map begins a transition from one
zoom level to another, either as a result of user interaction or the use of methods such as Map#jumpTo.
Properties
data (EventData)
: Original event data, if fired interactively
Zoom end event. This event is emitted just after the map completes a transition from one
zoom level to another, either as a result of user interaction or the use of methods such as Map#jumpTo.
Properties
data (EventData)
: Original event data, if fired interactively
Boxzoom start event. This event is emitted at the start of a box zoom interaction.
Properties
Boxzoom end event. This event is emitted at the end of a box zoom interaction
Properties
originalEvent (Event)
: the original DOM event
boxZoomBounds (LngLatBounds)
: the bounds of the box zoom target
Boxzoom cancel event. This event is emitted when the user cancels a box zoom interaction,
or when the box zoom does not meet the minimum size threshold.
Properties
Rotate end event. This event is emitted at the end of a user-initiated rotate interaction.
Properties
Rotate event. This event is emitted repeatedly during a user-initiated rotate interaction.
Properties
Rotate start event. This event is emitted at the start of a user-initiated rotate interaction.
Properties
Drag event. This event is emitted repeatedly during a user-initiated pan interaction.
Properties
Drag end event. This event is emitted at the end of a user-initiated pan interaction.
Properties
Drag start event. This event is emitted at the start of a user-initiated pan interaction.
Properties
Pitch event. This event is emitted whenever the map's pitch changes.
Properties
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) );
Parameters
Example
var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
Static Members
Convert an array to a LngLat object, or return an existing LngLat object
unchanged.
Parameters
Returns
LngLat:
LngLat object or original input
Example
var arr = [-73.9749, 40.7736];
var ll = mapboxgl.LngLat.convert(arr);
ll;
Instance Members
Return a new LngLat object whose longitude is wrapped to the range (-180, 180).
Returns
LngLat:
wrapped LngLat object
Example
var ll = new mapboxgl.LngLat(286.0251, 40.7736);
var wrapped = ll.wrap();
wrapped.lng;
Return a LngLat as an array
Returns
array:
[lng, lat]
Example
var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
ll.toArray();
Return a LngLat as a string
Returns
string:
"LngLat(lng, lat)"
Example
var ll = new mapboxgl.LngLat(-73.9749, 40.7736);
ll.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
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 an array to a LngLatBounds object, or return an existing
LngLatBounds object unchanged.
Calls LngLat#convert internally to convert arrays as LngLat values.
Parameters
Returns
LngLatBounds:
LngLatBounds object or original input
Example
var arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
var llb = mapboxgl.LngLatBounds.convert(arr);
llb;
Instance Members
Extend the bounds to include a given LngLat or LngLatBounds.
Parameters
Returns
LngLatBounds:
this
Get the point equidistant from this box's corners
Returns
LngLat:
centerpoint
Example
var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.getCenter();
Get southwest corner
Returns
LngLat:
southwest
Get northeast corner
Returns
LngLat:
northeast
Get northwest corner
Returns
LngLat:
northwest
Get southeast corner
Returns
LngLat:
southeast
Get west edge longitude
Returns
number:
west
Get south edge latitude
Returns
number:
south
Get east edge longitude
Returns
number:
east
Get north edge latitude
Returns
number:
north
Return a LngLatBounds as an array
Returns
array:
[lng, lat]
Example
var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.toArray();
Return a LngLatBounds as a string
Returns
string:
"LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))"
Example
var llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
llb.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
| 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'}));
Creates a geolocation control
new Geolocate(options: [
Object])
Parameters
| 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'}));
Creates an attribution control
new Attribution(options: [
Object])
Parameters
| 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
Add this control to the map, returning the control itself
for chaining. This will insert the control's DOM element into
the map's DOM element if the control has a position specified.
Parameters
Returns
Control:
this
Remove this control from the map it has been added to.
Returns
Control:
this
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
Instance Members
Returns the current enabled/disabled state of the "box zoom" interaction.
Returns
boolean:
enabled state
Returns true if the "box zoom" interaction is currently active, i.e. currently being used.
Returns
boolean:
active state
Enable the "box zoom" interaction.
Example
map.boxZoom.enable();
Disable the "box zoom" interaction.
Example
map.boxZoom.disable();
The ScrollZoomHandler allows a user to zoom the map by scrolling.
new ScrollZoomHandler(map: )
Parameters
Instance Members
The DragPanHandler allows a user to pan the map by clicking and dragging
the cursor.
new DragPanHandler(map: )
Parameters
Instance Members
Returns the current enabled/disabled state of the "drag to pan" interaction.
Returns
boolean:
enabled state
Returns true if the "drag to pan" interaction is currently active, i.e. currently being used.
Returns
boolean:
active state
Enable the "drag to pan" interaction.
Example
map.dragPan.enable();
Disable the "drag to pan" interaction.
Example
map.dragPan.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
Instance Members
Returns the current enabled/disabled state of the "drag to rotate" interaction.
Returns
boolean:
enabled state
Returns true if the "drag to rotate" interaction is currently active, i.e. currently being used.
Returns
boolean:
active state
Enable the "drag to rotate" interaction.
Example
map.dragRotate.enable();
Disable the "drag to rotate" interaction.
Example
map.dragRotate.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
Instance Members
Returns the current enabled/disabled state of keyboard interaction.
Returns
boolean:
enabled state
Enable the ability to interact with the map using keyboard input.
Example
map.keyboard.enable();
Disable the ability to interact with the map using keyboard input.
Example
map.keyboard.disable();
The DoubleClickZoomHandler allows a user to zoom the map around point by
double clicking.
new DoubleClickZoomHandler(map: )
Parameters
Instance Members
Returns the current enabled/disabled state of the "double click to zoom" interaction.
Returns
boolean:
enabled state
Enable the "double click to zoom" interaction.
Example
map.doubleClickZoom.enable();
Disable the "double click to zoom" interaction.
Example
map.doubleClickZoom.disable();
The TouchZoomRotateHandler allows a user to zoom and rotate the map by
pinching on a touchscreen.
new TouchZoomRotateHandler(map: )
Parameters
Instance Members
Returns the current enabled/disabled state of the "pinch to rotate and zoom" interaction.
Returns
boolean:
enabled state
Enable the "pinch to rotate and zoom" interaction.
Example
map.touchZoomRotate.enable();
Disable the "pinch to rotate and zoom" interaction.
Example
map.touchZoomRotate.disable();
Disable the "pinch to rotate" interaction, leaving the "pinch to zoom"
interaction enabled.
Example
map.touchZoomRotate.disableRotation();
Enable the "pinch to rotate" interaction, undoing a call to
disableRotation.
Example
map.touchZoomRotate.enable();
map.touchZoomRotate.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
| 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);
map.removeSource('some id');
Instance Members
Update source geojson data and rerender map
Parameters
data ((Object | string)) A GeoJSON data object or URL to it. The latter is preferable in case of large GeoJSON files.
Returns
GeoJSONSource:
this
Create a Video data source instance given an options object
new VideoSource(options: [
Object])
Parameters
| 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);
map.removeSource('some id');
Instance Members
Return the HTML video element.
Returns
Object:
setCoordinates
(coordinates)
Update video coordinates and rerender map
Parameters
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.
Returns
VideoSource:
this
Create an Image source instance given an options object
new ImageSource(options: [
Object])
Parameters
| 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);
map.removeSource('some id');
Instance Members
setCoordinates
(coordinates)
Update image coordinates and rerender map
Parameters
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.
Returns
ImageSource:
this
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.
Options common to Map#jumpTo, Map#easeTo, and Map#flyTo, controlling the destination
location, zoom level, bearing and pitch.
Properties
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)
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
offset (Array)
: point, origin of movement relative to map center
animate (boolean)
: When set to false, no animation happens
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
Creates a popup component
Parameters
| 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
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
Subscribe to a specified event with a listener function the latter gets the data object that was passed to fire and additionally target and type properties
Parameters
listener (Function) Function to be called when the event is fired
Returns
Object:
this
Remove a event listener
Parameters
type ([string]) Event type. If none is specified, remove all listeners
listener ([Function]) Function to be called when the event is fired. If none is specified all listeners are removed
Returns
Object:
this
Call a function once when an event has fired
Parameters
listener (Function) Function to be called once when the event is fired
Returns
Object:
this
Fire event of a given string type with the given data object
Parameters
Returns
Object:
this
Check if an event is registered to a type
Parameters
Returns
boolean:
true
if there is at least one registered listener for events of type
type