Skip to content

MapLibreMap

Defined in: ui/map.ts:450

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, see MapLibreMapOptions for the full list. Then MapLibre GL JS initializes the map on the page and returns your Map object.

Example

let map = new 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
     }
    }
  }
});

See

Display a map

Accessors

repaint

Get Signature

get repaint(): boolean

Defined in: ui/map.ts:2548

Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance.

Returns

boolean


showOverdrawInspector

Get Signature

get showOverdrawInspector(): boolean

Defined in: ui/map.ts:2535

Gets and sets a Boolean indicating whether the map should color-code each fragment to show how many times it has been shaded. White fragments have been shaded 8 or more times. Black fragments have been shaded 0 times. This information is useful for debugging.

Returns

boolean


showPadding

Get Signature

get showPadding(): boolean

Defined in: ui/map.ts:2519

Gets and sets a Boolean indicating whether the map will visualize the padding offsets.

Returns

boolean


showTileBoundaries

Get Signature

get showTileBoundaries(): boolean

Defined in: ui/map.ts:2506

Gets and sets a Boolean indicating whether the map will render an outline around each tile and the tile ID. These tile boundaries are useful for debugging.

The uncompressed file size of the first vector source is drawn in the top left corner of each tile, next to the tile ID.

Example
map.showTileBoundaries = true;
Returns

boolean


version

Get Signature

get version(): string

Defined in: ui/map.ts:2570

Returns the package version of the library

Returns

string

Package version of the library

Events

off()

Call Signature

off<T>(type: T, layer: string, listener: (ev: MapLayerEventType[T] & Object) => void): this

Defined in: ui/map.ts:1464

Removes an event listener for events previously added with Map#on.

Type Parameters
Type Parameter
T extends keyof MapLayerEventType
Parameters
Parameter Type Description
type T The event type previously used to install the listener.
layer string The layer ID or listener previously used to install the listener.
listener (ev: MapLayerEventType[T] & Object) => void The function previously installed as a listener.
Returns

this

Overrides

Camera.off

Call Signature

off<T>(type: T, layers: string[], listener: (ev: MapLayerEventType[T] & Object) => void): this

Defined in: ui/map.ts:1477

Overload of the off method that allows to remove an event created with multiple layers. Provide the same layer IDs as to on or once, when the listener was registered.

Type Parameters
Type Parameter
T extends keyof MapLayerEventType
Parameters
Parameter Type Description
type T The type of the event.
layers string[] The layer IDs previously used to install the listener.
listener (ev: MapLayerEventType[T] & Object) => void The function previously installed as a listener.
Returns

this

Overrides

Camera.off

Call Signature

off<T>(type: T, listener: (ev: MapEventType[T] & Object) => void): this

Defined in: ui/map.ts:1488

Overload of the off method that allows to remove an event created without specifying a layer.

Type Parameters
Type Parameter
T extends keyof MapEventType
Parameters
Parameter Type Description
type T The type of the event.
listener (ev: MapEventType[T] & Object) => void The function previously installed as a listener.
Returns

this

Overrides

Camera.off

Call Signature

off(type: string, listener: Listener): this

Defined in: ui/map.ts:1498

Overload of the off method that allows to remove an event created without specifying a layer.

Parameters
Parameter Type Description
type string The type of the event.
listener Listener The function previously installed as a listener.
Returns

this

Overrides

Camera.off


on()

on(type: string, listener: Listener): this

Defined in: ui/map.ts:1435

Adds a listener for events of a specified type, optionally limited to features in a specified style layer(s). See MapEventType and MapLayerEventType for a full list of events and their description.

Event Compatible with layerId
mousedown yes
mouseup yes
mouseover yes
mouseout yes
mousemove yes
mouseenter yes (required)
mouseleave yes (required)
click yes
dblclick yes
contextmenu yes
touchstart yes
touchend yes
touchcancel yes
wheel
resize
remove
touchmove
movestart
move
moveend
dragstart
drag
dragend
zoomstart
zoom
zoomend
rotatestart
rotate
rotateend
pitchstart
pitch
pitchend
boxzoomstart
boxzoomend
boxzoomcancel
webglcontextlost
webglcontextrestored
load
render
idle
error
data
styledata
sourcedata
dataloading
styledataloading
sourcedataloading
styleimagemissing
dataabort
sourcedataabort

Parameters

Parameter Type Description
type string The event type to listen for. Events compatible with the optional layerId parameter are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.
listener Listener The function to be called when the event is fired.

Returns

this

Examples

// Set an event listener that will fire
// when the map has finished loading
map.on('load', () => {
  // Once the map has finished loading,
  // add a new layer
  map.addLayer({
    id: 'points-of-interest',
    source: {
      type: 'vector',
      url: 'https://maplibre.org/maplibre-style-spec/'
    },
    'source-layer': 'poi_label',
    type: 'circle',
    paint: {
      // MapLibre Style Specification paint properties
    },
    layout: {
      // MapLibre Style Specification layout properties
    }
  });
});
// Set an event listener that will fire
// when a feature on the countries layer of the map is clicked
map.on('click', 'countries', (e) => {
  new Popup()
    .setLngLat(e.lngLat)
    .setHTML(`Country name: ${e.features[0].properties.name}`)
    .addTo(map);
});

See

Overrides

Camera.on


once()

once(type: string, listener?: Listener): Promise<any> | MapLibreMap

Defined in: ui/map.ts:1452

Adds a listener that will be called only once to a specified event type, optionally limited to features in a specified style layer.

Parameters

Parameter Type Description
type string The event type to listen for; one of 'mousedown', 'mouseup', 'click', 'dblclick', 'mousemove', 'mouseenter', 'mouseleave', 'mouseover', 'mouseout', 'contextmenu', 'touchstart', 'touchend', or 'touchcancel'. mouseenter and mouseover events are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. mouseleave and mouseout events are triggered when the cursor leaves a visible portion of the specified layer, or leaves the map canvas.
listener? Listener The function to be called when the event is fired.

Returns

Promise<any> | MapLibreMap

this if listener is provided, promise otherwise to allow easier usage of async/await

Overrides

Camera.once

Methods

addControl()

addControl(control: IControl, position?: ControlPosition): MapLibreMap

Defined in: ui/map.ts:794

Adds an IControl to the map, calling control.onAdd(this).

An ErrorEvent will be fired if the image parameter is invalid.

Parameters

Parameter Type Description
control IControl The IControl to add.
position? ControlPosition position on the map to which the control will be added. Valid values are 'top-left', 'top-right', 'bottom-left', and 'bottom-right'. Defaults to 'top-right'.

Returns

MapLibreMap

Example

Add zoom and rotation controls to the map.

map.addControl(new NavigationControl());

See

Display map navigation controls


addLayerToBucket()

addLayerToBucket(layer: AddLayerObject, bucketId?: number): this

Defined in: ui/map.ts:1948

Adds a style layer. Uses the specified layer bucket, ensuring correct ordering of layers.

Parameters

Parameter Type Description
layer AddLayerObject Layer to add.
bucketId? number Numerical id of the bucket where the layer will be added. This determines layer ordering.

Returns

this


addSource()

addSource(id: string, source: RasterSourceSpecification | RasterSourceSpecificationWithRetina): this

Defined in: ui/map.ts:1762

Adds a source to the map's style.

Events triggered:

Triggers the source.add event.

Parameters

Parameter Type Description
id string The ID of the source to add. Must not conflict with existing sources.
source RasterSourceSpecification | RasterSourceSpecificationWithRetina The source object, conforming to the MapLibre Style Specification's source definition or CanvasSourceSpecification.

Returns

this

Examples

map.addSource('my-data', {
  type: 'vector',
  url: 'https://demotiles.maplibre.org/tiles/tiles.json'
});
map.addSource('my-data', {
  "type": "geojson",
  "data": {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [-77.0323, 38.9131]
    },
    "properties": {
      "title": "Mapbox DC",
      "marker-symbol": "monument"
    }
  }
});

See

GeoJSON source: Add live realtime data


areTilesLoaded()

areTilesLoaded(): boolean

Defined in: ui/map.ts:1800

Returns a Boolean indicating whether all tiles in the viewport from all sources on the style are loaded.

Returns

boolean

A Boolean indicating whether all tiles are loaded.

Example

let tilesLoaded = map.areTilesLoaded();

calculateCameraOptionsFromTo()

calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo?: number): CameraOptions

Defined in: ui/map.ts:874

Calculates pitch, zoom and bearing for looking at newCenter with the camera position being newCenter and returns them as CameraOptions.

Parameters

Parameter Type Description
from LngLat The camera to look from
altitudeFrom number The altitude of the camera to look from
to LngLat The center to look at
altitudeTo? number Optional altitude of the center to look at. If none given the ground height will be used.

Returns

CameraOptions

the calculated camera options

Overrides

Camera.calculateCameraOptionsFromTo


cameraForBounds()

cameraForBounds(bounds: LngLatBoundsLike, options?: CameraForBoundsOptions): CenterZoomBearing

Defined in: ui/camera.ts:720

Parameters

Parameter Type Description
bounds LngLatBoundsLike Calculate the center for these bounds in the viewport and use the highest zoom level up to and including Map#getMaxZoom() that fits in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point.
options? CameraForBoundsOptions Options object

Returns

CenterZoomBearing

If map is able to fit to provided bounds, returns center, zoom, and bearing. If map is unable to fit, method will warn and return undefined.

Example

let bbox = [[-79, 43], [-73, 45]];
let newCameraTransform = map.cameraForBounds(bbox, {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});

Inherited from

Camera.cameraForBounds


easeTo()

easeTo(options: AnimationOptions & CenterZoomBearing & object & object & object, eventData?: any): this

Defined in: ui/camera.ts:1022

Changes any combination of center, zoom, bearing, pitch, roll, and padding with an animated transition between old and new values. The map will retain its current values for any details not specified in options.

Note: The transition will happen instantly if the user has enabled the reduced motion accessibility feature enabled in their operating system, unless options includes essential: true.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, zoomend, pitchstart, pitch, pitchend, rollstart, roll, rollend, and rotate.

Parameters

Parameter Type Description
options AnimationOptions & CenterZoomBearing & object & object & object Options describing the destination and animation of the transition. Accepts CameraOptions and AnimationOptions.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

See

Navigate the map with game-like controls

Inherited from

Camera.easeTo


fitBounds()

fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this

Defined in: ui/camera.ts:815

Pans and zooms the map to contain its visible area within the specified geographical bounds. This function will also reset the map's bearing to 0 if bearing is nonzero.

Triggers the following events: movestart and moveend.

Parameters

Parameter Type Description
bounds LngLatBoundsLike Center these bounds in the viewport and use the highest zoom level up to and including Map#getMaxZoom() that fits them in the viewport. Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point.
options? FitBoundsOptions Options supports all properties from AnimationOptions and CameraOptions in addition to the fields below.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

let bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});

See

Fit a map to a bounding box

Inherited from

Camera.fitBounds


fitScreenCoordinates()

fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: FitBoundsOptions, eventData?: any): this

Defined in: ui/camera.ts:841

Pans, rotates and zooms the map to to fit the box made by points p0 and p1 once the map is rotated to the specified bearing. To zoom without rotating, pass in the current map bearing.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, zoomend and rotate.

Parameters

Parameter Type Description
p0 PointLike First point on screen, in pixel coordinates
p1 PointLike Second point on screen, in pixel coordinates
bearing number Desired map bearing at end of animation, in degrees
options? FitBoundsOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

let p0 = [220, 400];
let p1 = [500, 900];
map.fitScreenCoordinates(p0, p1, map.getBearing(), {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});

See

Used by BoxZoomHandler

Inherited from

Camera.fitScreenCoordinates


flyTo()

flyTo(options: FlyToOptions, eventData?: any): this

Defined in: ui/camera.ts:1260

Changes any combination of center, zoom, bearing, pitch, and roll, animating the transition along a curve that evokes flight. The animation seamlessly incorporates zooming and panning to help the user maintain her bearings even after traversing a great distance.

Note: The animation will be skipped, and this will behave equivalently to jumpTo if the user has the reduced motion accessibility feature enabled in their operating system, unless 'options' includes essential: true.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, zoomend, pitchstart, pitch, pitchend, rollstart, roll, rollend, and rotate.

Parameters

Parameter Type Description
options FlyToOptions Options describing the destination and animation of the transition. Accepts CameraOptions, AnimationOptions, and the following additional options.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

// fly with default options to null island
map.flyTo({center: [0, 0], zoom: 9});
// using flyTo options
map.flyTo({
  center: [0, 0],
  zoom: 9,
  speed: 0.2,
  curve: 1,
  easing(t) {
    return t;
  }
});

See

Inherited from

Camera.flyTo


getBearing()

getBearing(): number

Defined in: ui/camera.ts:531

Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

Returns

number

The map's current bearing.

See

Navigate the map with game-like controls

Inherited from

Camera.getBearing


getBounds()

getBounds(): LngLatBounds

Defined in: ui/map.ts:988

Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.

Returns

LngLatBounds

The geographical bounds of the map as LngLatBounds.

Example

let bounds = map.getBounds();

getCameraTargetElevation()

getCameraTargetElevation(): number

Defined in: ui/map.ts:2580

Returns the elevation for the point where the camera is looking. This value corresponds to: "meters above sea level" * "exaggeration"

Returns

number

The elevation.


getCanvas()

getCanvas(): HTMLCanvasElement

Defined in: ui/map.ts:2093

Returns the map's <canvas> element.

Returns

HTMLCanvasElement

The map's <canvas> element.

See


getCanvasContainer()

getCanvasContainer(): HTMLElement

Defined in: ui/map.ts:2081

Returns the HTML element containing the map's <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 from child elements such as the <canvas>, but not from map controls.

Returns

HTMLElement

The container of the map's <canvas>.

See

Create a draggable point


getCenter()

getCenter(): LngLat

Defined in: ui/camera.ts:363

Returns the map's geographical centerpoint.

Returns

LngLat

The map's geographical centerpoint.

Example

Return a LngLat object such as {lng: 0, lat: 0}

let center = map.getCenter();
// access longitude and latitude values directly
let {lng, lat} = map.getCenter();

Inherited from

Camera.getCenter


getContainer()

getContainer(): HTMLElement

Defined in: ui/map.ts:2065

Returns the map's containing HTML element.

Returns

HTMLElement

The map's container.


getLayer()

getLayer(id: string): StyleLayer

Defined in: ui/map.ts:2017

Returns the layer with the specified ID in the map's style.

Parameters

Parameter Type Description
id string The ID of the layer to get.

Returns

StyleLayer

The layer with the specified ID, or undefined if the ID corresponds to no existing layers.

Example

let stateDataLayer = map.getLayer('state-data');

See


getLayersOrder()

getLayersOrder(): string[]

Defined in: ui/map.ts:2031

Return the ids of all layers currently in the style, including custom layers, in order.

Returns

string[]

ids of layers, in order

Example

const orderedLayerIds = map.getLayersOrder();

getMaxBounds()

getMaxBounds(): LngLatBounds

Defined in: ui/map.ts:1000

Returns the maximum geographical bounds the map is constrained to, or null if none set.

Returns

LngLatBounds

The map object.

Example

let maxBounds = map.getMaxBounds();

getMaxPitch()

getMaxPitch(): number

Defined in: ui/map.ts:1189

Returns the map's maximum allowable pitch.

Returns

number

The maxPitch


getMaxZoom()

getMaxZoom(): number

Defined in: ui/map.ts:1114

Returns the map's maximum allowable zoom level.

Returns

number

The maxZoom

Example

let maxZoom = map.getMaxZoom();

getMinPitch()

getMinPitch(): number

Defined in: ui/map.ts:1153

Returns the map's minimum allowable pitch.

Returns

number

The minPitch


getMinZoom()

getMinZoom(): number

Defined in: ui/map.ts:1074

Returns the map's minimum allowable zoom level.

Returns

number

minZoom

Example

let minZoom = map.getMinZoom();

getPadding()

getPadding(): PaddingOptions

Defined in: ui/camera.ts:561

Returns the current padding applied around the map viewport.

Returns

PaddingOptions

The current padding around the map viewport.

Inherited from

Camera.getPadding


getPitch()

getPitch(): number

Defined in: ui/camera.ts:665

Returns the map's current pitch (tilt).

Returns

number

The map's current pitch, measured in degrees away from the plane of the screen.

Inherited from

Camera.getPitch


getPixelRatio()

getPixelRatio(): number

Defined in: ui/map.ts:962

Returns the map's pixel ratio. Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.

Returns

number

The pixel ratio.


getRenderWorldCopies()

getRenderWorldCopies(): boolean

Defined in: ui/map.ts:1207

Returns the state of renderWorldCopies. If true, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to false:

  • When the map is zoomed out far enough that a single representation of the world does not fill the map's entire container, there will be blank space beyond 180 and -180 degrees longitude.
  • Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level.

Returns

boolean

The renderWorldCopies

Example

let worldCopiesRendered = map.getRenderWorldCopies();

See

Render world copies


getRoll()

getRoll(): number

Defined in: ui/camera.ts:687

Returns the map's current roll angle.

Returns

number

The map's current roll, measured in degrees about the camera boresight.

Inherited from

Camera.getRoll


getSource()

getSource<TSource>(id: string): TSource

Defined in: ui/map.ts:1849

Returns the source with the specified ID in the map's style.

This method is often used to update a source using the instance members for the relevant source type as defined in classes that derive from Source. For example, setting the data for a GeoJSON source or updating the url and coordinates of an image source.

Type Parameters

Type Parameter
TSource extends Source

Parameters

Parameter Type Description
id string The ID of the source to get.

Returns

TSource

The style source with the specified ID or undefined if the ID corresponds to no existing sources. The shape of the object varies by source type. A list of options for each source type is available on the MapLibre Style Specification's Sources page.

Example

let sourceObject = map.getSource('points');

See


getStyle()

getStyle(): StyleSpecification

Defined in: ui/map.ts:1704

Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style.

Returns

StyleSpecification

The map's style JSON object.

Example

let styleJson = map.getStyle();

getZoom()

getZoom(): number

Defined in: ui/camera.ts:435

Returns the map's current zoom level.

Returns

number

The map's current zoom level.

Example

map.getZoom();

Inherited from

Camera.getZoom


hasControl()

hasControl(control: IControl): boolean

Defined in: ui/map.ts:870

Checks if a control exists on the map.

Parameters

Parameter Type Description
control IControl The IControl to check.

Returns

boolean

true if map contains control.

Example

// Define a new navigation control.
let navigation = new NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Check that the navigation control exists on the map.
map.hasControl(navigation);

isMoving()

isMoving(): boolean

Defined in: ui/map.ts:1275

Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.

Returns

boolean

true if the map is moving.

Example

let isMoving = map.isMoving();

isRotating()

isRotating(): boolean

Defined in: ui/map.ts:1299

Returns true if the map is rotating due to a camera animation or user gesture.

Returns

boolean

true if the map is rotating.

Example

map.isRotating();

isSourceLoaded()

isSourceLoaded(id: string): boolean

Defined in: ui/map.ts:1781

Returns a Boolean indicating whether the source is loaded. Returns true if the source with the given ID in the map's style has no outstanding network requests, otherwise false.

A ErrorEvent event will be fired if there is no source wit the specified ID.

Parameters

Parameter Type Description
id string The ID of the source to be checked.

Returns

boolean

A Boolean indicating whether the source is loaded.

Example

let sourceLoaded = map.isSourceLoaded('bathymetry-data');

isStyleLoaded()

isStyleLoaded(): boolean | void

Defined in: ui/map.ts:1720

Returns a Boolean indicating whether the map's style is fully loaded.

Returns

boolean | void

A Boolean indicating whether the style is fully loaded.

Example

let styleLoadStatus = map.isStyleLoaded();

isZooming()

isZooming(): boolean

Defined in: ui/map.ts:1287

Returns true if the map is zooming due to a camera animation or user gesture.

Returns

boolean

true if the map is zooming.

Example

let isZooming = map.isZooming();

jumpTo()

jumpTo(options: JumpToOptions, eventData?: any): this

Defined in: ui/camera.ts:900

Changes any combination of center, zoom, bearing, pitch, and roll, without an animated transition. The map will retain its current values for any details not specified in options.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, zoomend, pitchstart, pitch, pitchend, rollstart, roll, rollend and rotate.

Parameters

Parameter Type Description
options JumpToOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

// jump to coordinates at current zoom
map.jumpTo({center: [0, 0]});
// jump with zoom, pitch, and bearing options
map.jumpTo({
  center: [0, 0],
  zoom: 8,
  pitch: 45,
  bearing: 90
});

See

Inherited from

Camera.jumpTo


listens()

listens(type: string): boolean

Defined in: util/evented.ts:167

Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type.

Parameters

Parameter Type Description
type string The event type

Returns

boolean

true if there is at least one registered listener for specified event type, false otherwise

Inherited from

Camera.listens


loaded()

loaded(): boolean

Defined in: ui/map.ts:2247

Returns a Boolean indicating whether the map is fully loaded.

Returns false if the style is not yet fully loaded, or if there has been a change to the sources or style that has not yet fully loaded.

Returns

boolean

A Boolean indicating whether the map is fully loaded.


moveLayerToBucket()

moveLayerToBucket(layerId: string, buckedId: number): this

Defined in: ui/map.ts:1960

Move a style layer. Uses the specified layer bucket, ensuring correct ordering of layers.

Parameters

Parameter Type
layerId string
buckedId number

Returns

this


panBy()

panBy(offset: PointLike, options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:393

Pans the map by the specified offset.

Triggers the following events: movestart and moveend.

Parameters

Parameter Type Description
offset PointLike x and y coordinates by which to pan the map.
options? AnimationOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

See

Navigate the map with game-like controls

Inherited from

Camera.panBy


panTo()

panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:414

Pans the map to the specified location with an animated transition.

Triggers the following events: movestart and moveend.

Parameters

Parameter Type Description
lnglat LngLatLike The location to pan the map to.
options? AnimationOptions Options describing the destination and animation of the transition.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

map.panTo([-74, 38]);
// Specify that the panTo animation should last 5000 milliseconds.
map.panTo([-74, 38], {duration: 5000});

See

Update a feature in realtime

Inherited from

Camera.panTo


project()

project(lnglat: LngLatLike): Point

Defined in: ui/map.ts:1245

Returns a Point representing pixel coordinates, relative to the map's container, that correspond to the specified geographical location.

Parameters

Parameter Type Description
lnglat LngLatLike The geographical location to project.

Returns

Point

The Point corresponding to lnglat, relative to the map's container.

Example

let coordinate = [-122.420679, 37.772537];
let point = map.project(coordinate);

redraw()

redraw(): this

Defined in: ui/map.ts:2406

Force a synchronous redraw of the map.

Returns

this

Example

map.redraw();

remove()

remove(): void

Defined in: ui/map.ts:2427

Clean up and release all internal resources associated with this map.

This includes DOM elements, event bindings, web workers, and WebGL resources.

Use this method when you are done using the map and wish to ensure that it no longer consumes browser resources. Afterwards, you must not call any other methods on the map.

Returns

void


removeControl()

removeControl(control: IControl): MapLibreMap

Defined in: ui/map.ts:839

Removes the control from the map.

An ErrorEvent will be fired if the image parameter is invalid.

Parameters

Parameter Type Description
control IControl The IControl to remove.

Returns

MapLibreMap

Example

// Define a new navigation control.
let navigation = new NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Remove zoom and rotation controls from the map.
map.removeControl(navigation);

removeLayer()

removeLayer(id: string): this

Defined in: ui/map.ts:1997

Removes the layer with the given ID from the map's style.

An ErrorEvent will be fired if the image parameter is invalid.

Parameters

Parameter Type Description
id string The ID of the layer to remove

Returns

this

Example

If a layer with ID 'state-data' exists, remove it.

if (map.getLayer('state-data')) map.removeLayer('state-data');


removeSource()

removeSource(id: string): MapLibreMap

Defined in: ui/map.ts:1822

Removes a source from the map's style.

Parameters

Parameter Type Description
id string The ID of the source to remove.

Returns

MapLibreMap

Example

map.removeSource('bathymetry-data');

resetNorth()

resetNorth(options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:615

Rotates the map so that north is up (0° bearing), with an animated transition.

Triggers the following events: movestart, moveend, and rotate.

Parameters

Parameter Type Description
options? AnimationOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Inherited from

Camera.resetNorth


resetNorthPitch()

resetNorthPitch(options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:628

Rotates and pitches the map so that north is up (0° bearing) and pitch and roll are 0°, with an animated transition.

Triggers the following events: movestart, move, moveend, pitchstart, pitch, pitchend, rollstart, roll, rollend, and rotate.

Parameters

Parameter Type Description
options? AnimationOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Inherited from

Camera.resetNorthPitch


resize()

resize(eventData?: any): MapLibreMap

Defined in: ui/map.ts:903

Resizes the map according to the dimensions of its container element.

Checks if the map container size changed and updates the map if it has changed. This method must be called after the map's container is resized programmatically or when the map is shown after being initially hidden with CSS.

Triggers the following events: movestart, move, moveend, and resize.

Parameters

Parameter Type Description
eventData? any Additional properties to be passed to movestart, move, resize, and moveend events that get triggered as a result of resize. This can be useful for differentiating the source of an event (for example, user-initiated or programmatically-triggered events).

Returns

MapLibreMap

Example

Resize the map when the map container is shown after being initially hidden with CSS.

let mapDiv = document.getElementById('map');
if (mapDiv.style.visibility === true) map.resize();


rotateTo()

rotateTo(bearing: number, options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:595

Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

Triggers the following events: movestart, moveend, and rotate.

Parameters

Parameter Type Description
bearing number The desired bearing.
options? AnimationOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Inherited from

Camera.rotateTo


setBearing()

setBearing(bearing: number, eventData?: any): this

Defined in: ui/camera.ts:551

Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

Equivalent to jumpTo({bearing: bearing}).

Triggers the following events: movestart, moveend, and rotate.

Parameters

Parameter Type Description
bearing number The desired bearing.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

Rotate the map to 90 degrees

map.setBearing(90);

Inherited from

Camera.setBearing


setCenter()

setCenter(center: LngLatLike, eventData?: any): MapLibreMap

Defined in: ui/camera.ts:379

Sets the map's geographical centerpoint. Equivalent to jumpTo({center: center}).

Triggers the following events: movestart and moveend.

Parameters

Parameter Type Description
center LngLatLike The centerpoint to set.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

MapLibreMap

Example

map.setCenter([-74, 38]);

Inherited from

Camera.setCenter


setEventedParent()

setEventedParent(parent?: Evented, data?: any): MapLibreMap

Defined in: util/evented.ts:180

Bubble all events fired by this instance of Evented to this parent instance of Evented.

Parameters

Parameter Type
parent? Evented
data? any

Returns

MapLibreMap

Inherited from

Camera.setEventedParent


setLayerZoomRange()

setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this

Defined in: ui/map.ts:2055

Sets the zoom extent for the specified style layer. The zoom extent includes the minimum zoom level and maximum zoom level) at which the layer will be rendered.

Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the minimum zoom level of the source layer because the data does not exist at those zoom levels. If the minimum zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style layer will not be rendered at all zoom levels in the zoom range.

Parameters

Parameter Type Description
layerId string The ID of the layer to which the zoom extent will be applied.
minzoom number The minimum zoom to set (0-24).
maxzoom number The maximum zoom to set (0-24).

Returns

this

Example

map.setLayerZoomRange('my-layer', 2, 5);

setMaxBounds()

setMaxBounds(bounds?: LngLatBoundsLike): MapLibreMap

Defined in: ui/map.ts:1025

Sets or clears the map's geographical bounds.

Pan and zoom operations are constrained within these bounds. If a pan or zoom is performed that would display regions outside these bounds, the map will instead display a position and zoom level as close as possible to the operation's request while still remaining within the bounds.

Parameters

Parameter Type Description
bounds? LngLatBoundsLike The maximum bounds to set. If null or undefined is provided, the function removes the map's maximum bounds.

Returns

MapLibreMap

Example

Define bounds that conform to the LngLatBoundsLike object as set the max bounds.

let bounds = [
  [-74.04728, 40.68392], // [west, south]
  [-73.91058, 40.87764]  // [east, north]
];
map.setMaxBounds(bounds);


setMaxPitch()

setMaxPitch(maxPitch?: number): MapLibreMap

Defined in: ui/map.ts:1167

Sets or clears the map's maximum pitch. If the map's current pitch is higher than the new maximum, the map will pitch to the new maximum.

A ErrorEvent event will be fired if maxPitch is out of bounds.

Parameters

Parameter Type Description
maxPitch? number The maximum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. If null or undefined is provided, the function removes the current maximum pitch (sets it to 60).

Returns

MapLibreMap


setMaxZoom()

setMaxZoom(maxZoom?: number): MapLibreMap

Defined in: ui/map.ts:1092

Sets or clears the map's maximum zoom level. If the map's current zoom level is higher than the new maximum, the map will zoom to the new maximum.

A ErrorEvent event will be fired if minZoom is out of bounds.

Parameters

Parameter Type Description
maxZoom? number The maximum zoom level to set. If null or undefined is provided, the function removes the current maximum zoom (sets it to 22).

Returns

MapLibreMap

Example

map.setMaxZoom(18.75);

setMinPitch()

setMinPitch(minPitch?: number): MapLibreMap

Defined in: ui/map.ts:1128

Sets or clears the map's minimum pitch. If the map's current pitch is lower than the new minimum, the map will pitch to the new minimum.

A ErrorEvent event will be fired if minPitch is out of bounds.

Parameters

Parameter Type Description
minPitch? number The minimum pitch to set (0-85). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. If null or undefined is provided, the function removes the current minimum pitch (i.e. sets it to 0).

Returns

MapLibreMap


setMinZoom()

setMinZoom(minZoom?: number): MapLibreMap

Defined in: ui/map.ts:1049

Sets or clears the map's minimum zoom level. If the map's current zoom level is lower than the new minimum, the map will zoom to the new minimum.

It is not always possible to zoom out and reach the set minZoom. Other factors such as map height may restrict zooming. For example, if the map is 512px tall it will not be possible to zoom below zoom 0 no matter what the minZoom is set to.

A ErrorEvent event will be fired if minZoom is out of bounds.

Parameters

Parameter Type Description
minZoom? number The minimum zoom level to set (-2 - 24). If null or undefined is provided, the function removes the current minimum zoom (i.e. sets it to -2).

Returns

MapLibreMap

Example

map.setMinZoom(12.25);

setPadding()

setPadding(padding: PaddingOptions, eventData?: any): this

Defined in: ui/camera.ts:580

Sets the padding in pixels around the viewport.

Equivalent to jumpTo({padding: padding}).

Triggers the following events: movestart and moveend.

Parameters

Parameter Type Description
padding PaddingOptions The desired padding.
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

Sets a left padding of 300px, and a top padding of 50px

map.setPadding({ left: 300, top: 50 });

Inherited from

Camera.setPadding


setPitch()

setPitch(pitch: number, eventData?: any): this

Defined in: ui/camera.ts:677

Sets the map's pitch (tilt). Equivalent to jumpTo({pitch: pitch}).

Triggers the following events: movestart, moveend, pitchstart, and pitchend.

Parameters

Parameter Type Description
pitch number The pitch to set, measured in degrees away from the plane of the screen (0-60).
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Inherited from

Camera.setPitch


setPixelRatio()

setPixelRatio(pixelRatio: number): void

Defined in: ui/map.ts:974

Sets the map's pixel ratio. This allows to override devicePixelRatio. After this call, the canvas' width attribute will be container.clientWidth * pixelRatio and its height attribute will be container.clientHeight * pixelRatio. Set this to null to disable devicePixelRatio override. Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.

Parameters

Parameter Type Description
pixelRatio number The pixel ratio.

Returns

void


setRenderWorldCopies()

setRenderWorldCopies(renderWorldCopies?: boolean): MapLibreMap

Defined in: ui/map.ts:1228

Sets the state of renderWorldCopies.

Parameters

Parameter Type Description
renderWorldCopies? boolean If true, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to false: - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire container, there will be blank space beyond 180 and -180 degrees longitude. - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level. undefined is treated as true, null is treated as false.

Returns

MapLibreMap

Example

map.setRenderWorldCopies(true);

See

Render world copies


setRoll()

setRoll(roll: number, eventData?: any): this

Defined in: ui/camera.ts:699

Sets the map's roll angle. Equivalent to jumpTo({roll: roll}).

Triggers the following events: movestart, moveend, rollstart, and rollend.

Parameters

Parameter Type Description
roll number The roll to set, measured in degrees about the camera boresight
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Inherited from

Camera.setRoll


setStyle()

setStyle(style: string | StyleSpecification, options?: StyleSwapOptions & StyleOptions): this

Defined in: ui/map.ts:1564

Updates the map's MapLibre style object with a new value.

If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites (images used for icons and patterns) and glyphs (fonts for label text) cannot be diffed. If the sprites or fonts used in the current style and the given style are different in any way, the map renderer will force a full update, removing the current style and building the given one from scratch.

Parameters

Parameter Type Description
style string | StyleSpecification A JSON object conforming to the schema described in the MapLibre Style Specification, or a URL to such JSON.
options? StyleSwapOptions & StyleOptions The options object.

Returns

this

Example

map.setStyle("https://demotiles.maplibre.org/style.json");

map.setStyle('https://demotiles.maplibre.org/style.json', {
  transformStyle: (previousStyle, nextStyle) => ({
      ...nextStyle,
      sources: {
          ...nextStyle.sources,
          // copy a source from previous style
          'osm': previousStyle.sources.osm
      },
      layers: [
          // background layer
          nextStyle.layers[0],
          // copy a layer from previous style
          previousStyle.layers[0],
          // other layers from the next style
          ...nextStyle.layers.slice(1).map(layer => {
              // hide the layers we don't need from demotiles style
              if (layer.id.startsWith('geolines')) {
                  layer.layout = {...layer.layout || {}, visibility: 'none'};
              // filter out US polygons
              } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {
                  layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];
              }
              return layer;
          })
      ]
  })
});

setTransformRequest()

setTransformRequest(transformRequest: RequestTransformFunction): this

Defined in: ui/map.ts:1602

Updates the requestManager's transform request with a new function

Parameters

Parameter Type Description
transformRequest RequestTransformFunction 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

Returns

this

Example

map.setTransformRequest((url: string, resourceType: string) => {});

setZoom()

setZoom(zoom: number, eventData?: any): this

Defined in: ui/camera.ts:452

Sets the map's zoom level. Equivalent to jumpTo({zoom: zoom}).

Triggers the following events: movestart, move, moveend, zoomstart, zoom, and zoomend.

Parameters

Parameter Type Description
zoom number The zoom level to set (0-20).
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

Zoom to the zoom level 5 without an animated transition

map.setZoom(5);

Inherited from

Camera.setZoom


snapToNorth()

snapToNorth(options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:653

Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the bearingSnap threshold).

Triggers the following events: movestart, moveend, and rotate.

Parameters

Parameter Type Description
options? AnimationOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Inherited from

Camera.snapToNorth


stop()

stop(): this

Defined in: ui/camera.ts:1458

Stops any animated transition underway.

Returns

this

Inherited from

Camera.stop


triggerRepaint()

triggerRepaint(): void

Defined in: ui/map.ts:2475

Trigger the rendering of a single frame. Use this method with custom layers to repaint the map when the layer changes. Calling this multiple times before the next frame is rendered will still result in only a single frame being rendered.

Returns

void

Example

map.triggerRepaint();

See


unproject()

unproject(point: PointLike): LngLat

Defined in: ui/map.ts:1263

Returns a LngLat representing geographical coordinates that correspond to the specified pixel coordinates.

Parameters

Parameter Type Description
point PointLike The pixel coordinates to unproject.

Returns

LngLat

The LngLat corresponding to point.

Example

map.on('click', (e) => {
  // When the map is clicked, get the geographic coordinate.
  let coordinate = map.unproject(e.point);
});

zoomIn()

zoomIn(options?: ZoomInOutOptions, eventData?: any): this

Defined in: ui/camera.ts:501

Increases the map's zoom level by 1.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, and zoomend.

Parameters

Parameter Type Description
options? ZoomInOutOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

Zoom the map in one level with a custom animation duration

map.zoomIn({duration: 1000});

Inherited from

Camera.zoomIn


zoomOut()

zoomOut(options?: ZoomInOutOptions, eventData?: any): this

Defined in: ui/camera.ts:519

Decreases the map's zoom level by 1.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, and zoomend.

Parameters

Parameter Type Description
options? ZoomInOutOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

Zoom the map out one level with a custom animation offset

map.zoomOut({offset: [80, 60]});

Inherited from

Camera.zoomOut


zoomTo()

zoomTo(zoom: number, options?: AnimationOptions, eventData?: any): this

Defined in: ui/camera.ts:476

Zooms the map to the specified zoom level, with an animated transition.

Triggers the following events: movestart, move, moveend, zoomstart, zoom, and zoomend.

Parameters

Parameter Type Description
zoom number The zoom level to transition to.
options? AnimationOptions Options object
eventData? any Additional properties to be added to event objects of events triggered by this method.

Returns

this

Example

// Zoom to the zoom level 5 without an animated transition
map.zoomTo(5);
// Zoom to the zoom level 8 with an animated transition
map.zoomTo(8, {
  duration: 2000,
  offset: [100, 50]
});

Inherited from

Camera.zoomTo

Properties

boxZoom

boxZoom: BoxZoomHandler

Defined in: ui/map.ts:519

The map's BoxZoomHandler, which implements zooming using a drag gesture with the Shift key pressed. Find more details and examples using boxZoom in the BoxZoomHandler section.


cancelPendingTileRequestsWhileZooming

cancelPendingTileRequestsWhileZooming: boolean

Defined in: ui/map.ts:570

The map's property which determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one. * If true, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom. * If false, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time.

Default Value

true

cooperativeGestures

cooperativeGestures: CooperativeGesturesHandler

Defined in: ui/map.ts:562

The map's CooperativeGesturesHandler, which allows the user to see cooperative gesture info when user tries to zoom in/out. Find more details and examples using cooperativeGestures in the CooperativeGesturesHandler section.


doubleClickZoom

doubleClickZoom: DoubleClickZoomHandler

Defined in: ui/map.ts:544

The map's DoubleClickZoomHandler, which allows the user to zoom by double clicking. Find more details and examples using doubleClickZoom in the DoubleClickZoomHandler section.


dragPan

dragPan: DragPanHandler

Defined in: ui/map.ts:532

The map's DragPanHandler, which implements dragging the map with a mouse or touch gesture. Find more details and examples using dragPan in the DragPanHandler section.


dragRotate

dragRotate: DragRotateHandler

Defined in: ui/map.ts:526

The map's DragRotateHandler, which implements rotating the map while dragging with the right mouse button or with the Control key pressed. Find more details and examples using dragRotate in the DragRotateHandler section.


keyboard

keyboard: KeyboardHandler

Defined in: ui/map.ts:538

The map's KeyboardHandler, which allows the user to zoom, rotate, and pan the map using keyboard shortcuts. Find more details and examples using keyboard in the KeyboardHandler section.


scrollZoom

scrollZoom: ScrollZoomHandler

Defined in: ui/map.ts:513

The map's ScrollZoomHandler, which implements zooming in and out with a scroll wheel or trackpad. Find more details and examples using scrollZoom in the ScrollZoomHandler section.


touchPitch

touchPitch: TwoFingersTouchPitchHandler

Defined in: ui/map.ts:556

The map's TwoFingersTouchPitchHandler, which allows the user to pitch the map with touch gestures. Find more details and examples using touchPitch in the TwoFingersTouchPitchHandler section.


touchZoomRotate

touchZoomRotate: TwoFingersTouchZoomRotateHandler

Defined in: ui/map.ts:550

The map's TwoFingersTouchZoomRotateHandler, which allows the user to zoom or rotate the map with touch gestures. Find more details and examples using touchZoomRotate in the TwoFingersTouchZoomRotateHandler section.


transformCameraUpdate

transformCameraUpdate: CameraUpdateTransformFunction

Defined in: ui/camera.ts:315

A callback used to defer camera updates or apply arbitrary constraints. If specified, this Camera instance can be used as a stateless component in React etc.

Inherited from

Camera.transformCameraUpdate