Skip to content

Class: Map

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 MapOptions 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

Hierarchy

  • Camera

Map

Accessors

repaint

get repaint(): boolean

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

Returns

boolean

Defined in

src/ui/map.ts:3299


showCollisionBoxes

get showCollisionBoxes(): boolean

Gets and sets a Boolean indicating whether the map will render boxes around all symbols in the data source, revealing which symbols were rendered or which were hidden due to collisions. This information is useful for debugging.

Returns

boolean

Defined in

src/ui/map.ts:3267


showOverdrawInspector

get showOverdrawInspector(): boolean

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

Defined in

src/ui/map.ts:3288


showPadding

get showPadding(): boolean

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

Returns

boolean

Defined in

src/ui/map.ts:3254


showTileBoundaries

get showTileBoundaries(): boolean

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.

Returns

boolean

Example

map.showTileBoundaries = true;

Defined in

src/ui/map.ts:3243


version

get version(): string

Returns the package version of the library

Returns

string

Package version of the library

Defined in

src/ui/map.ts:3314

Events

off

off<T>(type, layer, listener): this

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

Type parameters

Name Type
T extends keyof MapLayerEventType

Parameters

Name 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

this

Overrides

Camera.off

Defined in

src/ui/map.ts:1463

off<T>(type, listener): this

Overload of the off method that allows to listen to events without specifying a layer.

Type parameters

Name Type
T extends keyof MapEventType

Parameters

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

Returns

this

this

Overrides

Camera.off

Defined in

src/ui/map.ts:1475

off(type, listener): this

Overload of the off method that allows to listen to events without specifying a layer.

Parameters

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

Returns

this

this

Overrides

Camera.off

Defined in

src/ui/map.ts:1483


on

on<T>(type, layer, listener): Map

Adds a listener for events of a specified type, optionally limited to features in a specified style layer. 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

Type parameters

Name Type
T extends keyof MapLayerEventType

Parameters

Name Type Description
type T 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.
layer string The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location is within a visible feature in this layer. The event will have a features property containing an array of the matching features. If layer is not supplied, the event will not have a features property. Please note that many event types are not compatible with the optional layer parameter.
listener (ev: MapLayerEventType[T] & Object) => void The function to be called when the event is fired.

Returns

Map

this

Example

// Set an event listener that will fire
// when the map has finished loading
map.on('load', function() {
  // 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
    }
  });
});

Example

// 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

Defined in

src/ui/map.ts:1363

on<T>(type, listener): this

Overload of the on method that allows to listen to events without specifying a layer.

Type parameters

Name Type
T extends keyof MapEventType

Parameters

Name Type Description
type T The type of the event.
listener (ev: MapEventType[T] & Object) => void The listener callback.

Returns

this

this

Overrides

Camera.on

Defined in

src/ui/map.ts:1375

on(type, listener): this

Overload of the on method that allows to listen to events without specifying a layer.

Parameters

Name Type Description
type string The type of the event.
listener Listener The listener callback.

Returns

this

this

Overrides

Camera.on

Defined in

src/ui/map.ts:1383


once

once<T>(type, layer, listener?): Map | Promise<MapLayerEventType[T] & Object>

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

Type parameters

Name Type
T extends keyof MapLayerEventType

Parameters

Name Type Description
type T 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.
layer string The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible feature in this layer will trigger the listener. The event will have a features property containing an array of the matching features.
listener? (ev: MapLayerEventType[T] & Object) => void The function to be called when the event is fired.

Returns

Map | Promise<MapLayerEventType[T] & Object>

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

Overrides

Camera.once

Defined in

src/ui/map.ts:1418

once<T>(type, listener?): Promise<any> | Map

Overload of the once method that allows to listen to events without specifying a layer.

Type parameters

Name Type
T extends keyof MapEventType

Parameters

Name Type Description
type T The type of the event.
listener? (ev: MapEventType[T] & Object) => void The listener callback.

Returns

Promise<any> | Map

this

Overrides

Camera.once

Defined in

src/ui/map.ts:1430

once(type, listener?): Promise<any> | Map

Overload of the once method that allows to listen to events without specifying a layer.

Parameters

Name Type Description
type string The type of the event.
listener? Listener The listener callback.

Returns

Promise<any> | Map

this

Overrides

Camera.once

Defined in

src/ui/map.ts:1438

Methods

addControl

addControl(control, position?): Map

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

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

Parameters

Name 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

Map

this

Example

Add zoom and rotation controls to the map.

map.addControl(new NavigationControl());

See

Display map navigation controls

Defined in

src/ui/map.ts:708


addImage

addImage(id, image, options?): this

Add an image to the style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with icon-image, background-pattern, fill-pattern, or line-pattern.

A ErrorEvent event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image.

Parameters

Name Type Description
id string The ID of the image.
image ImageBitmap | HTMLImageElement | ImageData | StyleImageInterface | { data: Uint8Array | Uint8ClampedArray ; height: number ; width: number } The image as an HTMLImageElement, ImageData, ImageBitmap or object with width, height, and data properties with the same format as ImageData.
options Partial<StyleImageMetadata> Options object.

Returns

this

this

Example

// If the style's sprite does not already contain an image with ID 'cat',
// add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) {
   if (error) throw error;
   if (!map.hasImage('cat')) map.addImage('cat', image);
});

// Add a stretchable image that can be used with `icon-text-fit`
// In this example, the image is 600px wide by 400px high.
map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) {
   if (error) throw error;
   if (!map.hasImage('border-image')) {
     map.addImage('border-image', image, {
         content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border
         stretchX: [[16, 584]], // stretch everything horizontally except the 16px border
         stretchY: [[16, 384]], // stretch everything vertically except the 16px border
     });
   }
});

See

Defined in

src/ui/map.ts:2079


addLayer

addLayer(layer, beforeId?): Map

Adds a MapLibre style layer to the map's style.

A layer defines how data from a specified source will be styled. Read more about layer types and available paint and layout properties in the MapLibre Style Specification.

Parameters

Name Type Description
layer AddLayerObject The layer to add, conforming to either the MapLibre Style Specification's layer definition or, less commonly, the CustomLayerInterface specification. Can also be a layer definition with an embedded source definition. The MapLibre Style Specification's layer definition is appropriate for most layers.
beforeId? string The ID of an existing layer to insert the new layer before, resulting in the new layer appearing visually beneath the existing layer. If this argument is not specified, the layer will be appended to the end of the layers array and appear visually above all other layers.

Returns

Map

this

Example

Add a circle layer with a vector source

map.addLayer({
  id: 'points-of-interest',
  source: {
    type: 'vector',
    url: 'https://demotiles.maplibre.org/tiles/tiles.json'
  },
  'source-layer': 'poi_label',
  type: 'circle',
  paint: {
    // MapLibre Style Specification paint properties
  },
  layout: {
    // MapLibre Style Specification layout properties
  }
});

Example

Define a source before using it to create a new layer

map.addSource('state-data', {
  type: 'geojson',
  data: 'path/to/data.geojson'
});

map.addLayer({
  id: 'states',
  // References the GeoJSON source defined above
  // and does not require a `source-layer`
  source: 'state-data',
  type: 'symbol',
  layout: {
    // Set the label content to the
    // feature's `name` property
    text-field: ['get', 'name']
  }
});

Example

Add a new symbol layer before an existing layer

map.addLayer({
  id: 'states',
  // References a source that's already been defined
  source: 'state-data',
  type: 'symbol',
  layout: {
    // Set the label content to the
    // feature's `name` property
    text-field: ['get', 'name']
  }
// Add the layer before the existing `cities` layer
}, 'cities');

See

Defined in

src/ui/map.ts:2358


addSource

addSource(id, source): this

Adds a source to the map's style.

Events triggered:

Triggers the source.add event.

Parameters

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

Returns

this

this

Example

map.addSource('my-data', {
  type: 'vector',
  url: 'https://demotiles.maplibre.org/tiles/tiles.json'
});

Example

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

Defined in

src/ui/map.ts:1874


addSprite

addSprite(id, url, options?): this

Adds a sprite to the map's style. Fires the style event.

Parameters

Name Type Description
id string The ID of the sprite to add. Must not conflict with existing sprites.
url string The URL to load the sprite from
options StyleSetterOptions Options object.

Returns

this

this

Example

map.addSprite('sprite-two', 'http://example.com/sprite-two');

Defined in

src/ui/map.ts:2608


areTilesLoaded

areTilesLoaded(): boolean

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();

Defined in

src/ui/map.ts:1985


cameraForBounds

cameraForBounds(bounds, options?): CenterZoomBearing

Parameters

Name 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.
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

Defined in

src/ui/camera.ts:640


easeTo

easeTo(options, eventData?): this

Changes any combination of center, zoom, bearing, pitch, 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, and rotate.

Parameters

Name Type Description
options AnimationOptions & CenterZoomBearing & { around?: LngLatLike ; pitch?: number } & { delayEndEvents?: number ; padding?: number | RequireAtLeastOne<PaddingOptions> } & { easeId?: string ; noMoveStart?: boolean } 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

this

See

Navigate the map with game-like controls

Inherited from

Camera.easeTo

Defined in

src/ui/camera.ts:962


fitBounds

fitBounds(bounds, options?, eventData?): this

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

Name 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.
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

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

Defined in

src/ui/camera.ts:774


fitScreenCoordinates

fitScreenCoordinates(p0, p1, bearing, options?, eventData?): this

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

Name 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

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

Defined in

src/ui/camera.ts:804


flyTo

flyTo(options, eventData?): this

Changes any combination of center, zoom, bearing, and pitch, 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, and rotate.

Parameters

Name 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

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

Defined in

src/ui/camera.ts:1227


getBearing

getBearing(): number

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

Defined in

src/ui/camera.ts:486


getBounds

getBounds(): LngLatBounds

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();

Defined in

src/ui/map.ts:892


getCameraTargetElevation

getCameraTargetElevation(): number

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

Returns

number

The elevation.

Defined in

src/ui/map.ts:3324


getCanvas

getCanvas(): HTMLCanvasElement

Returns the map's <canvas> element.

Returns

HTMLCanvasElement

The map's <canvas> element.

See

Defined in

src/ui/map.ts:2849


getCanvasContainer

getCanvasContainer(): HTMLElement

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

Defined in

src/ui/map.ts:2837


getCenter

getCenter(): LngLat

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

Defined in

src/ui/camera.ts:327


getContainer

getContainer(): HTMLElement

Returns the map's containing HTML element.

Returns

HTMLElement

The map's container.

Defined in

src/ui/map.ts:2821


getFeatureState

getFeatureState(feature): any

Gets the state of a feature. A feature's state is a set of user-defined key-value pairs that are assigned to a feature at runtime. Features are identified by their feature.id attribute, which can be any number or string.

Note: To access the values in a feature's state object for the purposes of styling the feature, use the feature-state expression.

Parameters

Name Type Description
feature FeatureIdentifier Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.

Returns

any

The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.

Example

When the mouse moves over the my-layer layer, get the feature state for the feature under the mouse

map.on('mousemove', 'my-layer', function(e) {
  if (e.features.length > 0) {
    map.getFeatureState({
      source: 'my-source',
      sourceLayer: 'my-source-layer',
      id: e.features[0].id
    });
  }
});

Defined in

src/ui/map.ts:2812


getFilter

getFilter(layerId): void | FilterSpecification

Returns the filter applied to the specified style layer.

Parameters

Name Type Description
layerId string The ID of the style layer whose filter to get.

Returns

void | FilterSpecification

The layer's filter.

Defined in

src/ui/map.ts:2504


getGlyphs

getGlyphs(): string

Returns the value of the style's glyphs URL

Returns

string

glyphs Style's glyphs url

Defined in

src/ui/map.ts:2592


getImage

getImage(id): StyleImage

Returns an image, specified by ID, currently available in the map. This includes both images from the style's original sprite and any images that have been added at runtime using Map#addImage.

Parameters

Name Type Description
id string The ID of the image.

Returns

StyleImage

An image in the map with the specified ID.

Example

let coffeeShopIcon = map.getImage("coffee_cup");

Defined in

src/ui/map.ts:2194


getLayer

getLayer(id): StyleLayer

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

Parameters

Name 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

Defined in

src/ui/map.ts:2415


getLayersOrder

getLayersOrder(): string[]

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();

Defined in

src/ui/map.ts:2429


getLayoutProperty

getLayoutProperty(layerId, name): any

Returns the value of a layout property in the specified style layer.

Parameters

Name Type Description
layerId string The ID of the layer to get the layout property from.
name string The name of the layout property to get.

Returns

any

The value of the specified layout property.

Defined in

src/ui/map.ts:2566


getLight

getLight(): LightSpecification

Returns the value of the light object.

Returns

LightSpecification

light Light properties of the style.

Defined in

src/ui/map.ts:2688


getMaxBounds

getMaxBounds(): LngLatBounds

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();

Defined in

src/ui/map.ts:904


getMaxPitch

getMaxPitch(): number

Returns the map's maximum allowable pitch.

Returns

number

The maxPitch

Defined in

src/ui/map.ts:1094


getMaxZoom

getMaxZoom(): number

Returns the map's maximum allowable zoom level.

Returns

number

The maxZoom

Example

let maxZoom = map.getMaxZoom();

Defined in

src/ui/map.ts:1020


getMinPitch

getMinPitch(): number

Returns the map's minimum allowable pitch.

Returns

number

The minPitch

Defined in

src/ui/map.ts:1057


getMinZoom

getMinZoom(): number

Returns the map's minimum allowable zoom level.

Returns

number

minZoom

Example

let minZoom = map.getMinZoom();

Defined in

src/ui/map.ts:979


getPadding

getPadding(): PaddingOptions

Returns the current padding applied around the map viewport.

Returns

PaddingOptions

The current padding around the map viewport.

Inherited from

Camera.getPadding

Defined in

src/ui/camera.ts:515


getPaintProperty

getPaintProperty(layerId, name): unknown

Returns the value of a paint property in the specified style layer.

Parameters

Name Type Description
layerId string The ID of the layer to get the paint property from.
name string The name of a paint property to get.

Returns

unknown

The value of the specified paint property.

Defined in

src/ui/map.ts:2537


getPitch

getPitch(): number

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

Defined in

src/ui/camera.ts:609


getPixelRatio

getPixelRatio(): number

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

Returns

number

The pixel ratio.

Defined in

src/ui/map.ts:866


getRenderWorldCopies

getRenderWorldCopies(): boolean

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

Defined in

src/ui/map.ts:1110


getSource

getSource(id): Source

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 Sources. For example, setting the data for a GeoJSON source or updating the url and coordinates of an image source.

Parameters

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

Returns

Source

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

Defined in

src/ui/map.ts:2035


getSprite

getSprite(): { id: string ; url: string }[]

Returns the as-is value of the style's sprite.

Returns

{ id: string ; url: string }[]

style's sprite list of id-url pairs

Defined in

src/ui/map.ts:2640


getStyle

getStyle(): StyleSpecification

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();

Defined in

src/ui/map.ts:1815


getTerrain

getTerrain(): TerrainSpecification

Get the terrain-options if terrain is loaded

Returns

TerrainSpecification

the TerrainSpecification passed to setTerrain

Example

map.getTerrain(); // { source: 'terrain' };

Defined in

src/ui/map.ts:1971


getZoom

getZoom(): number

Returns the map's current zoom level.

Returns

number

The map's current zoom level.

Example

map.getZoom();

Inherited from

Camera.getZoom

Defined in

src/ui/camera.ts:394


hasControl

hasControl(control): boolean

Checks if a control exists on the map.

Parameters

Name 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);

Defined in

src/ui/map.ts:775


hasImage

hasImage(id): boolean

Check whether or not an image with a specific ID exists in the style. This checks both images in the style's original sprite and any images that have been added at runtime using Map#addImage.

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

Parameters

Name Type Description
id string The ID of the image.

Returns

boolean

A Boolean indicating whether the image exists.

Example

Check if an image with the ID 'cat' exists in the style's sprite.

let catIconExists = map.hasImage('cat');

Defined in

src/ui/map.ts:2214


isMoving

isMoving(): boolean

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();

Defined in

src/ui/map.ts:1177


isRotating

isRotating(): boolean

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();

Defined in

src/ui/map.ts:1201


isSourceLoaded

isSourceLoaded(id): boolean

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

Name 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');

Defined in

src/ui/map.ts:1893


isStyleLoaded

isStyleLoaded(): boolean | void

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();

Defined in

src/ui/map.ts:1831


isZooming

isZooming(): boolean

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();

Defined in

src/ui/map.ts:1189


jumpTo

jumpTo(options, eventData?): this

Changes any combination of center, zoom, bearing, and pitch, 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, and rotate.

Parameters

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

Returns

this

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

Defined in

src/ui/camera.ts:854


listImages

listImages(): string[]

Returns an Array of strings containing the IDs of all images currently available in the map. This includes both images from the style's original sprite and any images that have been added at runtime using Map#addImage.

Returns

string[]

An Array of strings containing the names of all sprites/images currently available in the map.

Example

let allImages = map.listImages();

Defined in

src/ui/map.ts:2273


listens

listens(type): boolean

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

Parameters

Name 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

Defined in

src/util/evented.ts:163


loadImage

loadImage(url): Promise<GetResourceResponse<ImageBitmap | HTMLImageElement>>

Load an image from an external URL to be used with Map#addImage. External domains must support CORS.

Parameters

Name Type Description
url string The URL of the image file. Image file must be in png, webp, or jpg format.

Returns

Promise<GetResourceResponse<ImageBitmap | HTMLImageElement>>

a promise that is resolved when the image is loaded

Example

Load an image from an external URL.

const response = await map.loadImage('http://placekitten.com/50/50');
// Add the loaded image to the style's sprite with the ID 'kitten'.
map.addImage('kitten', response.data);

See

Add an icon to the map

Defined in

src/ui/map.ts:2257


loaded

loaded(): boolean

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.

Defined in

src/ui/map.ts:2977


moveLayer

moveLayer(id, beforeId?): this

Moves a layer to a different z-position.

Parameters

Name Type Description
id string The ID of the layer to move.
beforeId? string The ID of an existing layer to insert the new layer before. When viewing the map, the id layer will appear beneath the beforeId layer. If beforeId is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.

Returns

this

this

Example

Move a layer with ID 'polygon' before the layer with ID 'country-label'. The polygon layer will appear beneath the country-label layer on the map.

map.moveLayer('polygon', 'country-label');

Defined in

src/ui/map.ts:2377


panBy

panBy(offset, options?, eventData?): this

Pans the map by the specified offset.

Triggers the following events: movestart and moveend.

Parameters

Name 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

this

See

Navigate the map with game-like controls

Inherited from

Camera.panBy

Defined in

src/ui/camera.ts:357


panTo

panTo(lnglat, options?, eventData?): this

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

Triggers the following events: movestart and moveend.

Parameters

Name 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

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

Defined in

src/ui/camera.ts:379


project

project(lnglat): Point

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

Parameters

Name 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);

Defined in

src/ui/map.ts:1147


queryRenderedFeatures

queryRenderedFeatures(geometryOrOptions?, options?): MapGeoJSONFeature[]

Returns an array of MapGeoJSONFeature objects representing visible features that satisfy the query parameters.

Parameters

Name Type Description
geometryOrOptions? PointLike | QueryRenderedFeaturesOptions | [PointLike, PointLike] (optional) The geometry of the query region: either a single point or southwest and northeast points describing a bounding box. Omitting this parameter (i.e. calling Map#queryRenderedFeatures with zero arguments, or with only a options argument) is equivalent to passing a bounding box encompassing the entire map viewport. The geometryOrOptions can receive a QueryRenderedFeaturesOptions only to support a situation where the function receives only one parameter which is the options parameter.
options? QueryRenderedFeaturesOptions (optional) Options object.

Returns

MapGeoJSONFeature[]

An array of MapGeoJSONFeature objects.

The properties value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only string and numeric property values are supported (i.e. null, Array, and Object values are not supported).

Each feature includes top-level layer, source, and sourceLayer properties. The layer property 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.

Only features that are currently rendered are included. Some features will not be included, like:

  • Features from layers whose visibility property is "none".
  • Features from layers whose zoom range excludes the current zoom level.
  • Symbol features that have been hidden due to text or icon collision.

Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0.

The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low zoom levels) are returned only once (though subject to the following caveat).

Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.

Example

Find all features at a point

let features = map.queryRenderedFeatures(
  [20, 35],
  { layers: ['my-layer-name'] }
);

Example

Find all features within a static bounding box

let features = map.queryRenderedFeatures(
  [[10, 20], [30, 50]],
  { layers: ['my-layer-name'] }
);

Example

Find all features within a bounding box around a point

let width = 10;
let height = 20;
let features = map.queryRenderedFeatures([
  [point.x - width / 2, point.y - height / 2],
  [point.x + width / 2, point.y + height / 2]
], { layers: ['my-layer-name'] });

Example

Query all rendered features from a single layer

let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });

See

Get features under the mouse pointer

Defined in

src/ui/map.ts:1589


querySourceFeatures

querySourceFeatures(sourceId, parameters?): MapGeoJSONFeature[]

Returns an array of MapGeoJSONFeature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.

Parameters

Name Type Description
sourceId string The ID of the vector tile or GeoJSON source to query.
parameters? QuerySourceFeatureOptions The options object.

Returns

MapGeoJSONFeature[]

An array of MapGeoJSONFeature objects.

In contrast to Map#queryRenderedFeatures, this function returns all features matching the query parameters, whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently visible viewport.

Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.

Example

Find all features in one source layer in a vector source

let features = map.querySourceFeatures('your-source-id', {
  sourceLayer: 'your-source-layer'
});

Defined in

src/ui/map.ts:1639


queryTerrainElevation

queryTerrainElevation(lngLatLike): number

Get the elevation difference between a given point and a point that is currently in the middle of the screen. This method should be used for proper positioning of custom 3d objects, as explained here Returns null if terrain is not enabled. This method is subject to change in Maplibre GL JS v5.

Parameters

Name Type Description
lngLatLike LngLatLike [x,y] or LngLat coordinates of the location

Returns

number

elevation offset in meters

Inherited from

Camera.queryTerrainElevation

Defined in

src/ui/camera.ts:1492


redraw

redraw(): this

Force a synchronous redraw of the map.

Returns

this

this

Example

map.redraw();

Defined in

src/ui/map.ts:3147


remove

remove(): void

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

Defined in

src/ui/map.ts:3168


removeControl

removeControl(control): Map

Removes the control from the map.

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

Parameters

Name Type Description
control IControl The IControl to remove.

Returns

Map

this

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);

Defined in

src/ui/map.ts:749


removeFeatureState

removeFeatureState(target, key?): this

Removes the state of a feature, setting it back to the default behavior. If only a target.source is specified, it will remove the state for all features from that source. If target.id is also specified, it will remove all keys for that feature's state. If key is also specified, it removes only that key from that feature's state. Features are identified by their feature.id attribute, which can be any number or string.

Parameters

Name Type Description
target FeatureIdentifier Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.
key? string (optional) The key in the feature state to reset.

Returns

this

this

Example

Reset the entire state object for all features in the my-source source

map.removeFeatureState({
  source: 'my-source'
});

Example

When the mouse leaves the my-layer layer, reset the entire state object for the feature under the mouse

map.on('mouseleave', 'my-layer', function(e) {
  map.removeFeatureState({
    source: 'my-source',
    sourceLayer: 'my-source-layer',
    id: e.features[0].id
  });
});

Example

When the mouse leaves the my-layer layer, reset only the hover key-value pair in the state for the feature under the mouse

map.on('mouseleave', 'my-layer', function(e) {
  map.removeFeatureState({
    source: 'my-source',
    sourceLayer: 'my-source-layer',
    id: e.features[0].id
  }, 'hover');
});

Defined in

src/ui/map.ts:2781


removeImage

removeImage(id): void

Remove an image from a style. This can be an image from the style's original sprite or any images that have been added at runtime using Map#addImage.

Parameters

Name Type Description
id string The ID of the image.

Returns

void

Example

// If an image with the ID 'cat' exists in
// the style's sprite, remove it.
if (map.hasImage('cat')) map.removeImage('cat');

Defined in

src/ui/map.ts:2237


removeLayer

removeLayer(id): this

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

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

Parameters

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

Returns

this

this

Example

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

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

Defined in

src/ui/map.ts:2396


removeSource

removeSource(id): Map

Removes a source from the map's style.

Parameters

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

Returns

Map

this

Example

map.removeSource('bathymetry-data');

Defined in

src/ui/map.ts:2008


removeSprite

removeSprite(id): Map

Removes the sprite from the map's style. Fires the style event.

Parameters

Name Type Description
id string The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be "default".

Returns

Map

this

Example

map.removeSprite('sprite-two');
map.removeSprite('default');

Defined in

src/ui/map.ts:2629


resetNorth

resetNorth(options?, eventData?): this

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

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

Parameters

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

Returns

this

this

Inherited from

Camera.resetNorth

Defined in

src/ui/camera.ts:564


resetNorthPitch

resetNorthPitch(options?, eventData?): this

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

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

Parameters

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

Returns

this

this

Inherited from

Camera.resetNorthPitch

Defined in

src/ui/camera.ts:578


resize

resize(eventData?): Map

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

Name 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

Map

this

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();

Defined in

src/ui/map.ts:807


rotateTo

rotateTo(bearing, options?, eventData?): this

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

Name 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

this

Inherited from

Camera.rotateTo

Defined in

src/ui/camera.ts:549


setBearing

setBearing(bearing, eventData?): this

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

Name 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

this

Example

Rotate the map to 90 degrees

map.setBearing(90);

Inherited from

Camera.setBearing

Defined in

src/ui/camera.ts:505


setCenter

setCenter(center, eventData?): Map

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

Triggers the following events: movestart and moveend.

Parameters

Name 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

Map

this

Example

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

Inherited from

Camera.setCenter

Defined in

src/ui/camera.ts:342


setEventedParent

setEventedParent(parent?, data?): Map

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

Parameters

Name Type
parent? Evented
data? any

Returns

Map

this

Inherited from

Camera.setEventedParent

Defined in

src/util/evented.ts:175


setFeatureState

setFeatureState(feature, state): this

Sets the state of a feature. A feature's state is a set of user-defined key-value pairs that are assigned to a feature at runtime. When using this method, the state object is merged with any existing key-value pairs in the feature's state. Features are identified by their feature.id attribute, which can be any number or string.

This method can only be used with sources that have a feature.id attribute. The feature.id attribute can be defined in three ways:

  • For vector or GeoJSON sources, including an id attribute in the original data file.
  • For vector or GeoJSON sources, using the promoteId option at the time the source is defined.
  • For GeoJSON sources, using the generateId option to auto-assign an id based on the feature's index in the source data. If you change feature data using map.getSource('some id').setData(..), you may need to re-apply state taking into account updated id values.

Note: You can use the feature-state expression to access the values in a feature's state object for the purposes of styling.

Parameters

Name Type Description
feature FeatureIdentifier Feature identifier. Feature objects returned from Map#queryRenderedFeatures or event handlers can be used as feature identifiers.
state any A set of key-value pairs. The values should be valid JSON types.

Returns

this

this

Example

// When the mouse moves over the `my-layer` layer, update
// the feature state for the feature under the mouse
map.on('mousemove', 'my-layer', function(e) {
  if (e.features.length > 0) {
    map.setFeatureState({
      source: 'my-source',
      sourceLayer: 'my-source-layer',
      id: e.features[0].id,
    }, {
      hover: true
    });
  }
});

See

Create a hover effect

Defined in

src/ui/map.ts:2729


setFilter

setFilter(layerId, filter?, options?): Map

Sets the filter for the specified style layer.

Filters control which features a style layer renders from its source. Any feature for which the filter expression evaluates to true will be rendered on the map. Those that are false will be hidden.

Use setFilter to show a subset of your source data.

To clear the filter, pass null or undefined as the second parameter.

Parameters

Name Type Description
layerId string The ID of the layer to which the filter will be applied.
filter? FilterSpecification The filter, conforming to the MapLibre Style Specification's filter definition. If null or undefined is provided, the function removes any existing filter from the layer.
options StyleSetterOptions Options object.

Returns

Map

this

Example

Display only features with the 'name' property 'USA'

map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);

Example

Display only features with five or more 'available-spots'

map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);

Example

Remove the filter for the 'bike-docks' style layer

map.setFilter('bike-docks', null);

See

Create a timeline animation

Defined in

src/ui/map.ts:2493


setGlyphs

setGlyphs(glyphsUrl, options?): this

Sets the value of the style's glyphs property.

Parameters

Name Type Description
glyphsUrl string Glyph URL to set. Must conform to the MapLibre Style Specification.
options StyleSetterOptions Options object.

Returns

this

this

Example

map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf');

Defined in

src/ui/map.ts:2581


setLayerZoomRange

setLayerZoomRange(layerId, minzoom, maxzoom): this

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

Name 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

this

Example

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

Defined in

src/ui/map.ts:2454


setLayoutProperty

setLayoutProperty(layerId, name, value, options?): this

Sets the value of a layout property in the specified style layer.

Parameters

Name Type Description
layerId string The ID of the layer to set the layout property in.
name string The name of the layout property to set.
value any The value of the layout property. Must be of a type appropriate for the property, as defined in the MapLibre Style Specification.
options StyleSetterOptions The options object.

Returns

this

this

Example

map.setLayoutProperty('my-layer', 'visibility', 'none');

Defined in

src/ui/map.ts:2554


setLight

setLight(light, options?): Map

Sets the any combination of light values.

Parameters

Name Type Description
light LightSpecification Light properties to set. Must conform to the MapLibre Style Specification.
options StyleSetterOptions Options object.

Returns

Map

this

Example

let layerVisibility = map.getLayoutProperty('my-layer', 'visibility');

Defined in

src/ui/map.ts:2677


setMaxBounds

setMaxBounds(bounds?): Map

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

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

Returns

Map

this

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);

Defined in

src/ui/map.ts:930


setMaxPitch

setMaxPitch(maxPitch?): Map

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

Name 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

Map

this

Defined in

src/ui/map.ts:1070


setMaxZoom

setMaxZoom(maxZoom?): Map

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

Name 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

Map

this

Example

map.setMaxZoom(18.75);

Defined in

src/ui/map.ts:996


setMinPitch

setMinPitch(minPitch?): Map

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

Name 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

Map

this

Defined in

src/ui/map.ts:1033


setMinZoom

setMinZoom(minZoom?): Map

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

Name 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

Map

this

Example

map.setMinZoom(12.25);

Defined in

src/ui/map.ts:955


setPadding

setPadding(padding, eventData?): this

Sets the padding in pixels around the viewport.

Equivalent to jumpTo({padding: padding}).

Triggers the following events: movestart and moveend.

Parameters

Name 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

this

Example

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

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

Inherited from

Camera.setPadding

Defined in

src/ui/camera.ts:533


setPaintProperty

setPaintProperty(layerId, name, value, options?): this

Sets the value of a paint property in the specified style layer.

Parameters

Name Type Description
layerId string The ID of the layer to set the paint property in.
name string The name of the paint property to set.
value any The value of the paint property to set. Must be of a type appropriate for the property, as defined in the MapLibre Style Specification. Pass null to unset the existing value.
options StyleSetterOptions Options object.

Returns

this

this

Example

map.setPaintProperty('my-layer', 'fill-color', '#faafee');

See

Defined in

src/ui/map.ts:2525


setPitch

setPitch(pitch, eventData?): this

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

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

Parameters

Name 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

this

Inherited from

Camera.setPitch

Defined in

src/ui/camera.ts:620


setPixelRatio

setPixelRatio(pixelRatio): void

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

Name Type Description
pixelRatio number The pixel ratio.

Returns

void

Defined in

src/ui/map.ts:878


setRenderWorldCopies

setRenderWorldCopies(renderWorldCopies?): Map

Sets the state of renderWorldCopies.

Parameters

Name 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

Map

this

Example

map.setRenderWorldCopies(true);

See

Render world copies

Defined in

src/ui/map.ts:1130


setSprite

setSprite(spriteUrl, options?): Map

Sets the value of the style's sprite property.

Parameters

Name Type Description
spriteUrl string Sprite URL to set.
options StyleSetterOptions Options object.

Returns

Map

this

Example

map.setSprite('YOUR_SPRITE_URL');

Defined in

src/ui/map.ts:2655


setStyle

setStyle(style, options?): this

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

Name 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

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;
          })
      ]
  })
});

Defined in

src/ui/map.ts:1691


setTerrain

setTerrain(options): this

Loads a 3D terrain mesh, based on a "raster-dem" source.

Triggers the terrain event.

Parameters

Name Type Description
options TerrainSpecification Options object.

Returns

this

this

Example

map.setTerrain({ source: 'terrain' });

Defined in

src/ui/map.ts:1914


setTransformRequest

setTransformRequest(transformRequest): this

Updates the requestManager's transform request with a new function

Parameters

Name 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

this

Example

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

Defined in

src/ui/map.ts:1720


setZoom

setZoom(zoom, eventData?): this

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

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

Parameters

Name 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

this

Example

Zoom to the zoom level 5 without an animated transition

map.setZoom(5);

Inherited from

Camera.setZoom

Defined in

src/ui/camera.ts:410


snapToNorth

snapToNorth(options?, eventData?): this

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

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

Returns

this

this

Inherited from

Camera.snapToNorth

Defined in

src/ui/camera.ts:597


stop

stop(): this

Stops any animated transition underway.

Returns

this

this

Inherited from

Camera.stop

Defined in

src/ui/camera.ts:1404


triggerRepaint

triggerRepaint(): void

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

Defined in

src/ui/map.ts:3215


unproject

unproject(point): LngLat

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

Parameters

Name Type Description
point PointLike The pixel coordinates to unproject.

Returns

LngLat

The LngLat corresponding to point.

Example

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

Defined in

src/ui/map.ts:1165


updateImage

updateImage(id, image): this

Update an existing image in a style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with icon-image, background-pattern, fill-pattern, or line-pattern.

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

Parameters

Name Type Description
id string The ID of the image.
image ImageBitmap | HTMLImageElement | ImageData | StyleImageInterface | { data: Uint8Array | Uint8ClampedArray ; height: number ; width: number } The image as an HTMLImageElement, ImageData, ImageBitmap or object with width, height, and data properties with the same format as ImageData.

Returns

this

this

Example

// If an image with the ID 'cat' already exists in the style's sprite,
// replace that image with a new image, 'other-cat-icon.png'.
if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');

Defined in

src/ui/map.ts:2146


zoomIn

zoomIn(options?, eventData?): this

Increases the map's zoom level by 1.

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

Parameters

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

Returns

this

this

Example

Zoom the map in one level with a custom animation duration

map.zoomIn({duration: 1000});

Inherited from

Camera.zoomIn

Defined in

src/ui/camera.ts:455


zoomOut

zoomOut(options?, eventData?): this

Decreases the map's zoom level by 1.

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

Parameters

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

Returns

this

this

Example

Zoom the map out one level with a custom animation offset

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

Inherited from

Camera.zoomOut

Defined in

src/ui/camera.ts:474


zoomTo

zoomTo(zoom, options?, eventData?): this

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

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

Parameters

Name 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

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

Defined in

src/ui/camera.ts:435

Properties

boxZoom

boxZoom: BoxZoomHandler

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.

Defined in

src/ui/map.ts:493


cooperativeGestures

cooperativeGestures: CooperativeGesturesHandler

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.

Defined in

src/ui/map.ts:536


doubleClickZoom

doubleClickZoom: DoubleClickZoomHandler

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

Defined in

src/ui/map.ts:518


dragPan

dragPan: DragPanHandler

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.

Defined in

src/ui/map.ts:506


dragRotate

dragRotate: DragRotateHandler

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.

Defined in

src/ui/map.ts:500


keyboard

keyboard: KeyboardHandler

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.

Defined in

src/ui/map.ts:512


scrollZoom

scrollZoom: ScrollZoomHandler

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.

Defined in

src/ui/map.ts:487


touchPitch

touchPitch: TwoFingersTouchPitchHandler

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.

Defined in

src/ui/map.ts:530


touchZoomRotate

touchZoomRotate: TwoFingersTouchZoomRotateHandler

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.

Defined in

src/ui/map.ts:524


transformCameraUpdate

transformCameraUpdate: CameraUpdateTransformFunction

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

Defined in

src/ui/camera.ts:296