MapLibre GL JS
API Reference
On This Page
Table of Contents
- IControl
- NavigationControl
- GeolocateControl
- AttributionControl
- ScaleControl
- FullscreenControl
- Popup
- Marker
IControl
Interface for interactive controls added to the map. This is a 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.
Examples
// 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;
};
onAdd
Register a control on the map and give it a chance to register event listeners and resources. This method is called by Map#addControl internally.
Parameters
map
Map the Map this control will be added to
Returns HTMLElement The control’s container element. This should be created by the control and returned by onAdd without being attached to the DOM: the map will insert the control’s element into the DOM as necessary.
onRemove
Unregister a control on the map and give it a chance to detach event listeners and resources. This method is called by Map#removeControl internally.
Parameters
map
Map the Map this control will be removed from
Returns undefined there is no required return value for this method
getDefaultPosition
Optionally provide a default position for this control. If this method
is implemented and Map#addControl is called without the position
parameter, the value returned by getDefaultPosition will be used as the
control’s position.
Returns string a control position, one of the values valid in addControl.
NavigationControl
A NavigationControl
control contains zoom buttons and a compass.
Parameters
options
Object?options.showCompass
Boolean Iftrue
the compass button is included. (optional, defaulttrue
)options.showZoom
Boolean Iftrue
the zoom-in and zoom-out buttons are included. (optional, defaulttrue
)options.visualizePitch
Boolean Iftrue
the pitch is visualized by rotating X-axis of compass. (optional, defaultfalse
)
Examples
var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-left');
GeolocateControl
Extends Evented
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 show as disabled.
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 interaction states:
- active - the map’s camera automatically updates as the user’s location changes, keeping the location dot in the center. Initial state and upon clicking the
GeolocateControl
button. - passive - the user’s location dot automatically updates, but the map’s camera does not. Occurs upon the user initiating a map movement.
- disabled - occurs if Geolocation is not available, disabled or denied.
These interaction states can’t be controlled programmatically, rather they are set based on user interactions.
Parameters
options
Object?options.positionOptions
Object A Geolocation API PositionOptions object. (optional, default{enableHighAccuracy:false,timeout:6000}
)options.fitBoundsOptions
Object A Map#fitBounds options object to use when the map is panned and zoomed to the user’s location. The default is to use amaxZoom
of 15 to limit how far the map will zoom in for very accurate locations. (optional, default{maxZoom:15}
)options.trackUserLocation
Object Iftrue
the Geolocate Control becomes a toggle button and when active the map will receive updates to the user’s location as it changes. (optional, defaultfalse
)options.showAccuracyCircle
Object By default, if showUserLocation istrue
, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user’s location. Set tofalse
to disable. Always disabled when showUserLocation isfalse
. (optional, defaulttrue
)options.showUserLocation
Object By default a dot will be shown on the map at the user’s location. Set tofalse
to disable. (optional, defaulttrue
)
Examples
map.addControl(new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
}));
trigger
Programmatically request and move the map to the user’s location.
Examples
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
map.on('load', function() {
geolocate.trigger();
});
Returns boolean Returns false
if called before control was added to a map, otherwise returns true
.
geolocate
Fired on each Geolocation API position update which returned as success.
Properties
data
Position The returned Position object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition().
Examples
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a geolocate event occurs.
geolocate.on('geolocate', function() {
console.log('A geolocate event has occurred.')
});
error
Fired on each Geolocation API position update which returned as an error.
Properties
data
PositionError The returned PositionError object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition().
Examples
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when an error event occurs.
geolocate.on('error', function() {
console.log('An error event has occurred.')
});
outofmaxbounds
Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds.
Properties
data
Position The returned Position object from the callback in Geolocation.getCurrentPosition() or Geolocation.watchPosition().
Examples
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when an outofmaxbounds event occurs.
geolocate.on('outofmaxbounds', function() {
console.log('An outofmaxbounds event has occurred.')
});
trackuserlocationstart
Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users’s location changes).
Examples
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a trackuserlocationstart event occurs.
geolocate.on('trackuserlocationstart', function() {
console.log('A trackuserlocationstart event has occurred.')
});
trackuserlocationend
Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not.
Examples
// Initialize the geolocate control.
var geolocate = new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
});
// Add the control to the map.
map.addControl(geolocate);
// Set an event listener that fires
// when a trackuserlocationend event occurs.
geolocate.on('trackuserlocationend', function() {
console.log('A trackuserlocationend event has occurred.')
});
AttributionControl
An AttributionControl
control presents the map’s attribution information.
Parameters
options
Object? (optional, default{}
)options.compact
boolean? Iftrue
, force a compact attribution that shows the full attribution on mouse hover. Iffalse
, force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide. Attribution should not be collapsed if it can comfortably fit on the map.compact
should only be used to modify default attribution when map size makes it impossible to fit default attribution and when the automatic compact resizing for default settings are not sufficient.options.customAttribution
(string | Array<string>)? String or strings to show in addition to any other attributions.
Examples
var map = new mapboxgl.Map({attributionControl: false})
.addControl(new mapboxgl.AttributionControl({
compact: true
}));
ScaleControl
A ScaleControl
control displays the ratio of a distance on the map to the corresponding distance on the ground.
Parameters
options
Object?
Examples
var scale = new mapboxgl.ScaleControl({
maxWidth: 80,
unit: 'imperial'
});
map.addControl(scale);
scale.setUnit('metric');
setUnit
Set the scale’s unit of the distance
Parameters
unit
Unit Unit of the distance ('imperial'
,'metric'
or'nautical'
).
FullscreenControl
A FullscreenControl
control contains a button for toggling the map in and out of fullscreen mode.
Parameters
options
Object?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.
Examples
map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));
Popup
Extends Evented
A popup component.
Parameters
options
Object?options.closeButton
boolean Iftrue
, a close button will appear in the top right corner of the popup. (optional, defaulttrue
)options.closeOnClick
boolean Iftrue
, the popup will closed when the map is clicked. (optional, defaulttrue
)options.closeOnMove
boolean Iftrue
, the popup will closed when the map moves. (optional, defaultfalse
)options.focusAfterOpen
boolean Iftrue
, the popup will try to focus the first focusable element inside the popup. (optional, defaulttrue
)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
**(numberPointLike Object)?** A pixel offset applied to the popup’s location specified as:- a single number specifying a distance from the popup’s location options.className
string? Space-separated CSS class names to add to popup containeroptions.maxWidth
string 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 (optional, default'240px'
)
Examples
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);
addTo
Adds the popup to a map.
Parameters
map
Map The Mapbox GL JS map to add the popup to.
Examples
new mapboxgl.Popup()
.setLngLat([0, 0])
.setHTML("<h1>Null Island</h1>")
.addTo(map);
Returns Popup this
isOpen
Returns boolean true
if the popup is open, false
if it is closed.
remove
Removes the popup from the map it has been added to.
Examples
var popup = new mapboxgl.Popup().addTo(map);
popup.remove();
Returns Popup this
getLngLat
Returns the geographical location of the popup’s anchor.
The longitude of the result may differ by a multiple of 360 degrees from the longitude previously
set by setLngLat
because Popup
wraps the anchor longitude across copies of the world to keep
the popup on screen.
Returns LngLat The geographical location of the popup’s anchor.
setLngLat
Sets the geographical location of the popup’s anchor, and moves the popup to it. Replaces trackPointer() behavior.
Parameters
lnglat
LngLatLike The geographical location to set as the popup’s anchor.
Returns Popup this
trackPointer
Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the setLngLat
behavior.
For most use cases, set closeOnClick
and closeButton
to false
.
Examples
var popup = new mapboxgl.Popup({ closeOnClick: false, closeButton: false })
.setHTML("<h1>Hello World!</h1>")
.trackPointer()
.addTo(map);
Returns Popup this
getElement
Returns the Popup
’s HTML element.
Examples
// Change the `Popup` element's font size
var popup = new mapboxgl.Popup()
.setLngLat([-96, 37.8])
.setHTML("<p>Hello World!</p>")
.addTo(map);
var popupElem = popup.getElement();
popupElem.style.fontSize = "25px";
Returns HTMLElement element
setText
Sets the popup’s content to a string of text.
This function creates a Text node in the DOM, so it cannot insert raw HTML. Use this method for security against XSS if the popup content is user-provided.
Parameters
text
string Textual content for the popup.
Examples
var popup = new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setText('Hello, world!')
.addTo(map);
Returns Popup this
setHTML
Sets the popup’s content to the HTML provided as a string.
This method does not perform HTML filtering or sanitization, and must be used only with trusted content. Consider Popup#setText if the content is an untrusted text string.
Parameters
html
string A string representing HTML content for the popup.
Examples
var popup = new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML("<h1>Hello World!</h1>")
.addTo(map);
Returns Popup this
getMaxWidth
Returns the popup’s maximum width.
Returns string The maximum width of the popup.
setMaxWidth
Sets the popup’s maximum width. This is setting the CSS property max-width
.
Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width
Parameters
maxWidth
string A string representing the value for the maximum width.
Returns Popup this
setDOMContent
Sets the popup’s content to the element provided as a DOM node.
Parameters
htmlNode
Node A DOM node to be used as content for the popup.
Examples
// create an element with the popup content
var div = window.document.createElement('div');
div.innerHTML = 'Hello, world!';
var popup = new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setDOMContent(div)
.addTo(map);
Returns Popup this
addClassName
Adds a CSS class to the popup container element.
Parameters
className
string Non-empty string with CSS class name to add to popup container
Examples
let popup = new mapboxgl.Popup()
popup.addClassName('some-class')
removeClassName
Removes a CSS class from the popup container element.
Parameters
className
string Non-empty string with CSS class name to remove from popup container
Examples
let popup = new mapboxgl.Popup()
popup.removeClassName('some-class')
setOffset
Sets the popup’s offset.
Parameters
offset
Offset? Sets the popup’s offset.
Returns Popup this
toggleClassName
Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.
Parameters
className
string Non-empty string with CSS class name to add/remove
Examples
let popup = new mapboxgl.Popup()
popup.toggleClassName('toggleClass')
Returns boolean if the class was removed return false, if class was added, then return true
open
Fired when the popup is opened manually or programatically.
Type: Object
Properties
popup
Popup object that was opened
Examples
// Create a popup
var popup = new mapboxgl.Popup();
// Set an event listener that will fire
// any time the popup is opened
popup.on('open', function(){
console.log('popup was opened');
});
close
Fired when the popup is closed manually or programatically.
Type: Object
Properties
popup
Popup object that was closed
Examples
// Create a popup
var popup = new mapboxgl.Popup();
// Set an event listener that will fire
// any time the popup is closed
popup.on('close', function(){
console.log('popup was closed');
});
Marker
Extends Evented
Creates a marker component
Parameters
options
Object?options.element
HTMLElement? DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.options.anchor
string 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'
. (optional, default'center'
)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 The color to use for the default marker if options.element is not provided. The default is light blue. (optional, default'#3FB1CE'
)options.scale
number The scale to use for the default marker if options.element is not provided. The default scale corresponds to a height of41px
and a width of27px
. (optional, default1
)options.draggable
boolean A boolean indicating whether or not a marker is able to be dragged to a new position on the map. (optional, defaultfalse
)options.clickTolerance
number The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map’s clickTolerance. (optional, default0
)options.rotation
number The rotation angle of the marker in degrees, relative to its respectiverotationAlignment
setting. A positive value will rotate the marker clockwise. (optional, default0
)options.pitchAlignment
stringmap
aligns theMarker
to the plane of the map.viewport
aligns theMarker
to the plane of the viewport.auto
automatically matches the value ofrotationAlignment
. (optional, default'auto'
)options.rotationAlignment
stringmap
aligns theMarker
’s rotation relative to the map, maintaining a bearing as the map rotates.viewport
aligns theMarker
’s rotation relative to the viewport, agnostic to map rotations.auto
is equivalent toviewport
. (optional, default'auto'
)
legacyOptions
Options?
Examples
var marker = new mapboxgl.Marker()
.setLngLat([30.5, 50.5])
.addTo(map);
// Set options
var marker = new mapboxgl.Marker({
color: "#FFFFFF",
draggable: true
}).setLngLat([30.5, 50.5])
.addTo(map);
addTo
Attaches the Marker
to a Map
object.
Parameters
map
Map The Mapbox GL JS map to add the marker to.
Examples
var marker = new mapboxgl.Marker()
.setLngLat([30.5, 50.5])
.addTo(map); // add the marker to the map
Returns Marker this
remove
Removes the marker from a map
Examples
var marker = new mapboxgl.Marker().addTo(map);
marker.remove();
Returns Marker this
getLngLat
Get the marker’s geographical location.
The longitude of the result may differ by a multiple of 360 degrees from the longitude previously
set by setLngLat
because Marker
wraps the anchor longitude across copies of the world to keep
the marker on screen.
Examples
// Store the marker's longitude and latitude coordinates in a variable
var lngLat = marker.getLngLat();
// Print the marker's longitude and latitude values in the console
console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )
Returns LngLat A LngLat describing the marker’s location.
setLngLat
Set the marker’s geographical position and move it.
Parameters
lnglat
LngLat A LngLat describing where the marker should be located.
Examples
// Create a new marker, set the longitude and latitude, and add it to the map
new mapboxgl.Marker()
.setLngLat([-65.017, -16.457])
.addTo(map);
Returns Marker this
getElement
Returns the Marker
’s HTML element.
Returns HTMLElement element
setPopup
Parameters
popup
Popup? An instance of the Popup class. If undefined or null, any popup set on this Marker instance is unset.
Examples
var marker = new mapboxgl.Marker()
.setLngLat([0, 0])
.setPopup(new mapboxgl.Popup().setHTML("<h1>Hello World!</h1>")) // add popup
.addTo(map);
Returns Marker this
getPopup
Returns the Popup instance that is bound to the Marker.
Examples
var marker = new mapboxgl.Marker()
.setLngLat([0, 0])
.setPopup(new mapboxgl.Popup().setHTML("<h1>Hello World!</h1>"))
.addTo(map);
console.log(marker.getPopup()); // return the popup instance
Returns Popup popup
togglePopup
Opens or closes the Popup instance that is bound to the Marker, depending on the current state of the Popup.
Examples
var marker = new mapboxgl.Marker()
.setLngLat([0, 0])
.setPopup(new mapboxgl.Popup().setHTML("<h1>Hello World!</h1>"))
.addTo(map);
marker.togglePopup(); // toggle popup open or closed
Returns Marker this
getOffset
Get the marker’s offset.
Returns Point The marker’s screen coordinates in pixels.
setOffset
Sets the offset of the marker
Parameters
offset
PointLike The offset in pixels as a PointLike object to apply relative to the element’s center. Negatives indicate left and up.
Returns Marker this
setDraggable
Sets the draggable
property and functionality of the marker
Parameters
shouldBeDraggable
boolean Turns drag functionality on/off (optional, defaultfalse
)
Returns Marker this
isDraggable
Returns true if the marker can be dragged
Returns boolean True if the marker is draggable.
setRotation
Sets the rotation
property of the marker.
Parameters
rotation
number The rotation angle of the marker (clockwise, in degrees), relative to its respective Marker#setRotationAlignment setting. (optional, default0
)
Returns Marker this
getRotation
Returns the current rotation angle of the marker (in degrees).
Returns number The current rotation angle of the marker.
setRotationAlignment
Sets the rotationAlignment
property of the marker.
Parameters
alignment
string Sets therotationAlignment
property of the marker. (optional, default'auto'
)
Returns Marker this
getRotationAlignment
Returns the current rotationAlignment
property of the marker.
Returns string The current rotational alignment of the marker.
setPitchAlignment
Sets the pitchAlignment
property of the marker.
Parameters
alignment
string? Sets thepitchAlignment
property of the marker. If alignment is ‘auto’, it will automatically matchrotationAlignment
.
Returns Marker this
getPitchAlignment
Returns the current pitchAlignment
property of the marker.
Returns string The current pitch alignment of the marker in degrees.
dragstart
Fired when dragging starts
Type: Object
Properties
marker
Marker object that is being dragged
drag
Fired while dragging
Type: Object
Properties
marker
Marker object that is being dragged
dragend
Fired when the marker is finished being dragged
Type: Object
Properties
marker
Marker object that was dragged