Map

The Map object represents the interactive map shown on your webpage. It offers various methods and properties that let you programmatically control and modify the map. It also handles user interactions through events. To create a map, specify a container along with configuration options — see MapOptions for the full list. Once initialized, gtswebsdkgl sets up the map and returns the corresponding Map object.

Since: 1.0.0
Extends: Camera
Defined: src/ui/map.ts

Constructor

new Map(options)
new Map(options: MapOptions)

Initializes a new map using the provided configuration options.

Parameters:

Name Type Description
options MapOptions Map configuration options. At minimum, a target option must be specified.

Example:

const style_object = {
   version: 8,
   sources: {},
   layers: []
  };

const map = new gtswebsdkgl.Map({
  target: 'map',
  center: [-122.420679, 37.772537],
  zoom: 13
  style: style_object,
  transformRequest: (url, resourceType) => {
    if (resourceType === 'Source' && url.startsWith('http://myHost')) {
        return {
                url: url.replace('http', 'https'),
                headers: { 'my-custom-header': true },
                credentials: 'include'
               };
           }
        }
  });

Properties

target
HTMLElement | string

Specifies the container for the map — either the HTML element itself or its ID. If not provided during initialization, the map can be rendered later by calling setTarget.

zoom?
optional zoom: number//(Default : 0)

The initial zoom level of the map. If no zoom value is provided in the constructor options, gtswebsdkgl will attempt to retrieve it from the map’s style object. If the style also lacks a zoom value, the default level will be 0.

style?
optional style: string || styleJSON

The map style used by the GTS Web SDK must be provided as a JSON object that conforms to the style specification supported by the SDK, or as a URL pointing to such a JSON file. If no style is specified, calling Map.setStyle is required to render the map.
The Map SDK has inbuilt support for osm, standard, and dark styles. The osm style is available for free, while the standard and dark styles require a valid GTS token. You can also add your own custom styles using a style JSON object or a style JSON URL.

token

An authentication key used to access the gtsmapsdk library and its associated APIs. This token verifies your identity and authorizes access to GTS map services. The token is mandatory only when using a GTS base map (such as standard or dark). If a GTS base map is used without a valid token, the map will not initialize or render data from the GTS platform.

mapboxAccessToken?
optional mapboxAccessToken: string | null

Specifies the access token required to use Mapbox base maps. This token authenticates your requests to Mapbox services such as style loading, tiles, and terrain data. It is only required if you are using a Mapbox-powered base map. If you are using other base maps (e.g., GTS maps), this property can be left null.

bounds?
optional bounds: LngLatBounds

Defines the initial bounds of the map. When specified, it takes precedence over the center and zoom options provided in the constructor.

Example:

const LngLatBounds = [
  [-74.025, 40.70], // Southwest: [lon, lat]
  [-73.925, 40.82] // Northeast: [lon, lat]
];

const map = new gtswebsdkgl.Map({
  target: 'map',
  bounds: LngLatBounds,
  style: style_object
  ...
});
attributionControl?
optional attributionControl: false |
{
  compact: true,
  customAttribution: '© MyCompany | Map data © contributors'
}

If specified, an AttributionControl is added to the map with the given options. If set to false, the attribution control will not be visible.

bearing?
optional bearing: number | 0

The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If bearing is not specified in the constructor options,gtswebsdkgl will look for it in the map's style object. If it is not specified in the style, either, it will default to 0.

bearingSnap?
optional bearingSnap: number | 7

Specifies the threshold (in degrees) that determines when the map’s bearing should snap to north. For example, with a bearingSnap value of 7, if the user rotates the map within 7 degrees of north, it will automatically snap back to true north.

boxZoom?
optional boxZoom: boolean (Default : true)

If true, the "box zoom" interaction is enabled.

cancelPendingTileRequestsWhileZooming?
optional cancelPendingTileRequestsWhileZooming: boolean //(Default : true)

Controls whether to cancel or retain tiles from previous zoom levels that are still loading when zooming in.

  • If set to true, tiles from lower (farther) zoom levels that haven’t finished loading will be canceled, which can improve performance on slower devices but may cause map details to appear more abruptly.
  • If set to false, tiles from previous zoom levels will continue loading, providing a smoother visual transition but requiring more rendering resources.

center?
optional center: LngLat //(Default : [0,0])

Specifies the starting geographic center of the map. If the center is not defined in the constructor options, gtswebsdkgl will try to obtain it from the map’s style object. If it’s not found there either, the map will default to the coordinates [0, 0].

centerClampedToGround?
optional centerClampedToGround: boolean

If set to true, the map automatically adjusts the center point’s elevation to match the terrain height (or to zero if terrain is disabled). When set to false, the center point remains fixed at sea level and does not update automatically. The default value is true. Set this to false if you want to keep the camera positioned above the ground when the pitch exceeds 90 degrees.

clickTolerance?
optional clickTolerance: number //(Default : 3)

The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).

hash?
optional hash: boolean | string //(Default : false)

If set to true, the map’s state — including zoom, center latitude, center longitude, bearing, and pitch — is synchronized with the hash fragment in the page’s URL.
For example: http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60
You can also include an optional string to use a parameter-style hash, such as: http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar
Here, foo represents a custom parameter, and bar is an arbitrary hash value separate from the map’s state.

interactive?
optional interactive: boolean //(Default : true)

If set to false, the map will not attach any mouse, touch, or keyboard event listeners, meaning it will remain completely non-interactive.

logoPosition?
optional logoPosition: ControlPosition //(Default : bottom-left)

Specifies the position of the gtswebsdkgl wordmark on the map. Valid values are "top-left", "top-right", "bottom-left", and "bottom-right".

optional gtswebsdkLogo: boolean //(Default : false)

If true, the gtswebsdkLogo logo will be shown.

maxBounds?
optional maxBounds: LngLatBounds

If set, the map will be constrained to the given bounds.
Accepts a LngLatBounds object, an array of LngLatLike objects in [southwest, northeast] order, or an array of numbers in [west, south, east, north] order.

Example:

const LngLatBounds = [
  [-74.025, 40.70], // Southwest: [lon, lat]
  [-73.925, 40.82] // Northeast: [lon, lat]
];

const map = new gtswebsdkgl.Map({
  target: 'map',
  maxBounds: LngLatBounds,
  style: style_object
  ...
});
maxCanvasSize?
optional maxCanvasSize: [number, number] //(Default : [4096, 4096])

Defines the maximum canvas dimensions as an array, where the first element represents the maximum width and the second represents the maximum height. It’s advised not to exceed the WebGL MAX_TEXTURE_SIZE limit for these values.

maxPitch?
optional maxPitch: number | null //(Default : 60)

The maximum pitch of the map (0-180).

maxTileCacheSize?
optional maxTileCacheSize: number | null //(Default : null)

Specifies the maximum number of tiles to store in the cache for a given source. If not set, the cache size is determined dynamically based on the current viewport, which can be configured using the maxTileCacheZoomLevels option in the constructor.

maxTileCacheZoomLevels?
optional maxTileCacheZoomLevels: number //(Default : 5)

The maximum number of zoom levels for which to store tiles for a given source. Tile cache dynamic size is calculated by multiplying maxTileCacheZoomLevels with the approximate number of tiles in the viewport for a given source.

maxZoom?
optional maxZoom: number | null //(Default : 22)

The maximum zoom level of the map (0-24).

minPitch?
optional minPitch: number | null //(Default : 0)

The minimum pitch of the map (0-180).

minZoom?
optional minZoom: number | null //(Default : 0)

The minimum zoom level of the map (0-24).

pitch
optional minZoom: number | null //(Default : 0)

Specifies the initial pitch (tilt) of the map in degrees from the screen plane, ranging from 0 to 85. If not provided in the constructor options, gtswebsdkgl will try to retrieve it from the map’s style object. If it’s not defined there either, the default value is 0. Note that pitch values above 60 degrees are experimental and may lead to rendering issues.

pitchWithRotate?
optional pitchWithRotate: boolean //(Default : true)

If set to false, the map’s pitch (tilt) control through the “drag to rotate” interaction will be disabled.

pixelRatio?
optional pixelRatio: number

Defines the pixel ratio used for rendering. The canvas width is calculated as container.clientWidth × pixelRatio, and the height as container.clientHeight × pixelRatio. If not specified, it defaults to the device’s devicePixelRatio.

refreshExpiredTiles?
optional refreshExpiredTiles: boolean //(Default : true)

If set to false, the map will not attempt to re-request tiles after they expire according to their HTTP cacheControl or expires headers.

renderWorldCopies?
optional renderWorldCopies: boolean //(Default : true)

If set to true, multiple copies of the world are rendered side by side beyond -180° and 180° longitude. If set to false, only a single instance of the world is displayed.

roll?
optional roll: number //(Default : 0)

Defines the initial roll angle of the map in degrees, measured counterclockwise around the camera’s boresight. If not specified in the constructor options, gtswebsdkgl attempts to retrieve it from the map’s style object. If it’s not defined there, the default value is 0.

rollEnabled?
optional rollEnabled: boolean //(Default : false)

If set to false, the map’s roll control through the “drag to rotate” interaction will be disabled.

scrollZoom?
optional scrollZoom: boolean | AroundCenterOptions //(Default : true)

If set to true, the “scroll to zoom” interaction will be enabled.

touchPitch?
optional touchPitch: boolean | AroundCenterOptions //({around: "center"})(Default : true)

If set to true, the “drag to pitch” interaction will be enabled.

touchZoomRotate?
optional touchZoomRotate: boolean | AroundCenterOptions //({around: "center"})(Default : true)

If set to true, the “pinch to rotate and zoom” interaction will be enabled.

trackResize?
optional trackResize: boolean //(Default : true)

If set to true, the map will automatically adjust its size when the browser window is resized.

transformCameraUpdate?
optional transformCameraUpdate: CameraUpdateTransformFunction | null//(Default : null)

A callback function that executes before the map’s camera moves as a result of user interaction or animation. It allows you to modify the upcoming center, zoom, pitch, and bearing values, and should return an object specifying any of these properties to override.

validateStyle?
optional validateStyle: boolean | null//(Default : true)

If set to false, style validation will be skipped. This option is useful in production environments.

language?
optional language: string | "en"//(Default : "en")

Specifies the language used for rendering map labels. Supported values are "en" and "local". This option applies only to GTS base maps (standard and dark).

enable3D?
optional enable3D: boolean | false//(Default : false)

Enables or disables 3D buildings on the map. This option is supported only for the standard and dark base maps. When enabled, buildings are rendered in 3D; otherwise, they are displayed in 2D.

pois?
optional pois: string[] | []//(Default : [all pois]])

Defines a list of Point-of-Interest (POI) categories to display on the map. This option is supported only when using the GTS base maps (standard and dark). If not specified, all available POI categories are shown by default.

Methods

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

Adds an control to the map, calling Map.addControl(control,position?).

Parameters:

Parameter Description
control The control you add to the map.
position? 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'.
addSource()
addSource(id: string, source: SourceSpecification | CanvasSourceSpecification): this: Source

Adds a new source to the map’s style, which provides the geographic data that layers use for visualization. A source defines how raw data (such as GeoJSON, vector tiles, or raster tiles) is accessed and made available for rendering. Each source can be linked to one or more layers that determine how the data appears on the map. For more details, examples, and supported source types, click here to learn more about Sources.

Parameters:

Parameter Description
id The ID of the source to add. Must not conflict with existing sources.
source The source object.

Ex:

map.addSource('my-data', {
    type: 'vector',
    url: '../tiles.json'
});
map.addSource('my-data', {
    "type": "geojson",
    "data": {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [-77.0323, 38.9131]
        },
        "properties": {
            "title": "DC",
            "marker-symbol": "monument"
        }
    }
});
addLayer()
addLayer(layer: AddLayerObject, beforeId?: string): Map

A layer defines how data from a specified source is visually represented on the map, including styles such as color, opacity, line width, and symbols. Each layer is associated with a source and controls how that data is rendered. For detailed usage, examples, and layer types, click here to learn more about Layers.

Parameters:

Parameter Description
layer Specifies a layer to be added to a Style.
beforeId? The ID of a layer to place the new layer before. If not provided, the new layer is added last and appears on top of all others.
addSprite()
addSprite(id: string, url: string, options: StyleSetterOptions): this

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

Parameters:

Parameter Description
id The ID of the sprite to add. Must not conflict with existing sprites.
url The URL to load the sprite from.

Ex:

map.addSprite('sprite-one', 'http://example.com/sprite-one');
addFeatureByWkt()
addFeatureByWkt(sourceId: string, wktData: string[] | string, geoKey?: string): this

Adds one or more features to the map from WKT (Well-Known Text) geometry. Accepts a WKT string or an array/JSON object containing WKT. When JSON is provided, use the optional geoKey to specify the geometry field.

Parameters:

Parameter Description
sourceId ID of the data source where features are added.
wktData A WKT string or array/JSON representing geometries.
geoKey (optional) For JSON input, property containing the WKT text.

Example:

map.addFeatureByWkt('roads-source', 'LINESTRING(0 0, 10 10)');

OR

map.addFeatureByWkt('roads-source', [ {"geom": "LINESTRING(0 0, 10 10)", "id": 1} ], 'geom');
addFeatureByflxyPolyline()
addFeatureByFlxyPolyline(sourceId: string, FlxypolylineData: string | object[], geoKey?: string): this

Adds one or more features using Flexy-encoded polyline strings. Supports single string input or JSON array. Use geoKey for identifying geometry fields inside JSON objects.

Parameters:

Parameter Description
sourceId ID of the data source where features will be added.
FlxypolylineData Flexy polyline string or JSON array of objects.
geoKey (optional) Defines the property containing Flexy polyline.

Example:

map.addFeatureByFlxyPolyline('route-source', 'flexyEncodedPolylineHere');

OR

var jsonData = [ { "geom": "flexyPolyline1", "link_dir": "1196191347T" }, { "geom": "flexyPolyline2", "link_dir": "1196191348T" } ];

map.addFeatureByFlxyPolyline('travel-source', jsonData, 'geom');
addFeatureByGeoJSON()
addFeatureByGeoJSON(sourceId: string, geojson: object): this

Adds one or more features to the map using a valid GeoJSON object. Supports Feature, FeatureCollection, or any GeoJSON geometry wrapped inside a Feature. The GeoJSON is directly injected into the target data source without any conversion. Fires the style event.

Parameters:

Parameter Description
sourceId ID of the data source where GeoJSON features will be added.
geojson A valid GeoJSON object (Feature or FeatureCollection) containing geometry and properties.

Example:

const geoData = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": { "type": "LineString", "coordinates": [[72.4,23.0],[72.6,23.1]] },
      "properties": { "road_id": 101 }
    },
    {
      "type": "Feature",
      "geometry": { "type": "Polygon", "coordinates": [[[72.5,23.0],[72.7,23.0],[72.7,23.2],[72.5,23.2],[72.5,23.0]]] },
      "properties": { "zone": "A" }
    }
  ]
};

map.addFeatureByGeoJSON('areas-source', geoData);
addFeatureByPolyline()
addFeatureByPolyline(sourceId: string, polylineData: string | object[], geoKey?: string): this

Adds features to the map using Google-encoded polylines. Supports single encoded string, array of strings, or JSON array. When JSON input is used, geoKey identifies the encoded polyline field.

Parameters:

Parameter Description
sourceId The ID of the data source to add features to.
polylineData Google encoded polyline string/array or JSON array.
geoKey (optional) If JSON, this specifies where the encoded polyline is stored.

Example:

map.addFeatureByPolyline('travel-source', 'gldwCycxnIum@y}Cum@khCky@snBwsBc{@{nCa]yoBwXqwBa]owB}pCqtAse@}gBulC');

OR

var jsonData = [ { "geom": "encodedPolyline1", "link_dir": "1196191347T" }, { "geom": "encodedPolyline2", "link_dir": "1196191348T" } ];

map.addFeatureByPolyline('travel-source', jsonData, 'geom');
areTilesLoaded()
areTilesLoaded(): boolean

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

Ex:

let tilesLoaded = map.areTilesLoaded();
calculateCameraOptionsFromCameraLngLatAltRotation()
calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat: LngLatLike, cameraAlt: number, bearing: number, pitch: number, roll?: number): CameraOptions

Given a camera position and rotation, calculates zoom and center point and returns them as CameraOptions.

Parameters:

Parameter Description
cameraLngLat The lng, lat of the camera to look from.
cameraAlt The altitude of the camera to look from, in meters above sea level.
bearing Bearing of the camera, in degrees.
pitch Pitch of the camera, in degrees.
roll? Roll of the camera, in degrees.

Returns:

Parameter Description
elevation? The elevation of the center point in meters above sea level.
pitch The desired pitch in degrees. The pitch is the angle towards the horizon measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon. Increasing the pitch value is often used to display 3D objects.
roll The desired roll in degrees. The roll is the angle about the camera boresight.

Ex:

// Calculate options to look from camera position(10°, 20°, 1000m) with
bearing = 90°, pitch = 30°, and roll = 45°;
const cameraLngLat = new LngLat(10, 20);
const cameraAltitude = 1000;
const bearing = 90;
const pitch = 30;
const roll = 45;
const cameraOptions = map.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAltitude, bearing, pitch, roll);
// Apply
map.jumpTo(cameraOptions);
calculateCameraOptionsFromTo()
calculateCameraOptionsFromTo(from: LngLat, altitudeFrom: number, to: LngLat, altitudeTo?: number): CameraOptions

Given a camera 'from' position and a position to look at (to), calculates zoom and camera rotation and returns them as CameraOptions.

Parameters:

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

Returns:

Parameter Description
elevation? The elevation of the center point in meters above sea level.
pitch The desired pitch in degrees. The pitch is the angle towards the horizon measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon. Increasing the pitch value is often used to display 3D objects.
roll The desired roll in degrees. The roll is the angle about the camera boresight.

Ex:

// Calculate options to look from (1°, 0°, 1000m) to (1°, 1°, 0m) with
const cameraLngLat = new LngLat(1, 0);
const cameraAltitude = 1000;
const targetLngLat = new LngLat(1, 1);
const targetAltitude = 0;
const cameraOptions = map.calculateCameraOptionsFromTo(cameraLngLat, cameraAltitude, targetLngLat, targetAltitude);
// Apply calculated options
map.jumpTo(cameraOptions);
easeTo()
easeTo(options: EaseToOptions, eventData?: any): this

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.
Triggers the following events: movestart, move, moveend, zoomstart, zoom, zoomend, pitchstart, pitch, pitchend, rollstart, roll, rollend, and rotate.

Parameters:

Parameter Description
options Options describing the destination and animation of the transition.

options:

options Description
center The geographic center point for the map view, specified as [longitude, latitude] coordinates
duration The length of time the animation should take to complete, specified in milliseconds
zoom The magnification level of the map using Mercator projection scaling
pitch The angle of the map's viewport, representing tilt from 0° (straight down) to 60°
roll The rotation angle of the map around the view direction axis
padding The desired padding.
essential When true, the animation will play regardless of user's prefers-reduced-motion accessibility setting

Ex:

map.easeTo({
  center:[-74.006, 40.7128],
  zoom: 10,
  pitch: 0,
  bearing: 0,
  duration: 2000,
  essential: true,
  padding: {
     top: 50,
     right: 50,
     bottom: 50,
     left: 50
  }
});
fitBounds()
fitBounds(bounds: LngLatBoundsLike, options?: FitBoundsOptions, eventData?: any): this

Moves and scales the map so that the specified geographical bounds fit entirely within the visible area. If the map currently has a nonzero bearing, it will be reset to 0.

Parameters:

Parameter Description
bounds The bounding box to fit within the map's viewport.
options Options describing the destination and animation of the transition.
eventData Optional data to be passed to any fired map events.

options:

options Description
center The geographic center point for the map view, specified as [longitude, latitude] coordinates
duration The length of time the animation should take to complete, specified in milliseconds
zoom The magnification level of the map using Mercator projection scaling
pitch The angle of the map's viewport, representing tilt from 0° (straight down) to 60°
roll The rotation angle of the map around the view direction axis
padding The desired padding to apply inside the viewport.
essential When true, the animation will play regardless of user's prefers-reduced-motion accessibility setting

Ex:

let bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
  padding: {top: 10, bottom:25, left: 15, right: 5}
});
fitScreenCoordinates()
fitScreenCoordinates(point0: PointLike, point1: PointLike, bearing: number, options?: CameraOptions | AnimationOptions, eventData?: any): this

Fits a set of two screen coordinates (in pixels) and an orientation (bearing) into the current viewport. This method is often used for scenarios like keeping two markers visible on screen. If the map currently has a nonzero pitch, it will be reset to 0.

Parameters:

Parameter Description
point0 The first screen coordinate (in pixels) to fit in the viewport.
point1 The second screen coordinate (in pixels) to fit in the viewport.
bearing The desired map rotation angle (in degrees).
options Options describing the animation and padding of the transition.
eventData Optional data to be passed to any fired map events.

options:

options Description
duration The length of time the animation should take to complete, specified in milliseconds.
easing A function to control the rate of animation.
padding The desired padding to apply inside the viewport.
essential When true, the animation will play regardless of user's prefers-reduced-motion accessibility setting

Ex:

let pixelPoint1 = [10, 10]; // top-left pixel
let pixelPoint2 = [200, 200]; // a pixel 200 units down and right
let rotation = 45; // 45-degree rotation
map.fitScreenCoordinates(pixelPoint1, pixelPoint2, rotation, {
  duration: 500,
  padding: 20
});
flyTo()
flyTo(options?: FlyToOptions, eventData?: any): this

Changes the map's center, zoom, bearing, and pitch with a smooth, **curved flight animation**, making the transition feel like an airplane flight. This is ideal for moving between distant locations gracefully.

Parameters:

Parameter Description
options Options describing the destination and animation of the flight.
eventData Optional data to be passed to any fired map events.

options:

options Description
center The geographic center point for the map view, specified as [longitude, latitude].
zoom The desired zoom level.
bearing The desired map rotation angle (in degrees).
pitch The desired map tilt angle (in degrees).
speed The desired speed of the flight, measured in units per second. A higher value is faster.
curve The zooming curve of the flight, controlling how sharply the animation "zooms out" in the middle of the flight.
duration The length of time the animation should take to complete, specified in **milliseconds**.
easing A function to control the rate of animation.
essential When true, the animation will play regardless of user's prefers-reduced-motion accessibility setting.

Ex:

map.flyTo({
  center: [-122.4194, 37.7749], // San Francisco, CA
  zoom: 14,
  pitch: 60,
  duration: 5000 // 5-second long flight
});
getBearing()
getBearing(): number

Returns the current **bearing** (rotation) of the map, measured in **degrees counter-clockwise** from North. A bearing of 0 or 360 is North, 90 is East, 180 is South, and 270 is West.

Returns:

Return Type Description
number The current map bearing in degrees.

Ex:

// Assuming the map has been rotated
let currentBearing = map.getBearing();
console.log(`Current Map Rotation: ${currentBearing}°`);
getBounds()
getBounds(): LngLatBounds

Returns the **geographical bounds** of the currently visible map area. This is a bounding box that encompasses everything currently in view on the map.

Returns:

Return Type Description
LngLatBounds A LngLatBounds object representing the southwest and northeast corners of the map's current visible viewport.

Ex:

// Get the current visible bounds
let currentBounds = map.getBounds();
// Output the coordinates of the southwest and northeast corners console.log("Southwest Corner:", currentBounds.getSouthWest());
console.log("Northeast Corner:", currentBounds.getNorthEast());
getCameraTargetElevation()
getCameraTargetElevation(): number

Returns the elevation of the map at the **center point of the viewport** (the camera target). This value is only relevant when the map style has an enabled terrain source and is using 3D rendering.

Returns:

Return Type Description
number The elevation of the map's center point, measured in **meters**. Returns 0 if no terrain is enabled or loaded.

Ex:

// Get the elevation at the current map center
let elevation = map.getCameraTargetElevation();
console.log(`Elevation at center: ${elevation} meters`); // e.g., 350.7
getCanvas()
getCanvas(): HTMLCanvasElement

Returns the **HTML <canvas> element** that is used by the map to render the WebGL view. This is the element where all map tiles, features, and imagery are drawn.

Returns:

Return Type Description
HTMLCanvasElement The raw <canvas> DOM element.

Ex:

let canvasElement = map.getCanvas();
// Use the canvas element for custom drawing or screenshot utilities let dataURL = canvasElement.toDataURL('image/png');
getCanvasContainer()
getCanvasContainer(): HTMLElement

Returns the **HTML element** that **immediately contains** the map's <canvas> element. This is typically an internal wrapper element.

Returns:

Return Type Description
HTMLElement The DOM element that contains the canvas.

Ex:

let canvasParent = map.getCanvasContainer();
// Apply styles or add elements to the container immediately surrounding the canvas canvasParent.style.border = '2px solid red';
getCenter()
getCenter(): LngLat

Returns the geographical **center point** of the map view. The center is defined by a longitude and latitude coordinate.

Returns:

Return Type Description
LngLat A LngLat object representing the map's current center.

Ex:

let center = map.getCenter();
console.log("Longitude:", center.lng, "Latitude:", center.lat);
getCenterClampedToGround()
getCenterClampedToGround(): LngLat

Returns the geographical center point of the map, but **clamped to the ground elevation**. If the map is pitched or has 3D terrain enabled, this is a more accurate center point on the surface than getCenter().

Returns:

Return Type Description
LngLat A LngLat object representing the map's center point projected onto the surface of the 3D terrain.

Ex:

// Use this when working with features precisely on the ground in 3D views
let groundCenter = map.getCenterClampedToGround();
getCenterElevation()
getCenterElevation(): number

Returns the elevation (in meters) of the map at the **center point of the viewport**. This is an alias for getCameraTargetElevation().

Returns:

Return Type Description
number The elevation of the map's center point in **meters**. Returns 0 if terrain is disabled.

Ex:

let elevation = map.getCenterElevation();
console.log(`Elevation at map center: ${elevation}m`);
getTarget()
getTarget(): HTMLElement

Returns the **outermost HTML element** that holds the entire map UI, including the canvas, controls (zoom buttons, attribution), and any custom overlays. This is the element originally passed to the Map constructor.

Returns:

Return Type Description
HTMLElement The top-level container DOM element of the map.

Ex:

let mapContainer = map.getTarget();
// Append a custom legend div to the top-level container
mapContainer.appendChild(myLegendDiv);
getFilter()
getFilter(layerId: string): Array | void

Returns the **filter** expression applied to a specific layer. Filters determine which features in a layer's source should be rendered.

Parameters:

Parameter Description
layerId The ID of the layer whose filter you want to retrieve.

Returns:

Return Type Description
Array<any> | void The filter array (an expression) if one is set, otherwise undefined.

Ex:

let currentFilter = map.getFilter('my-point-layer');
console.log("Current Filter:", currentFilter); // e.g., ["==", "type", "road"]
getImage()
getImage(id: string): MapImage | void

Returns a **MapImage** object previously added to the map's style with map.addImage(). This image can then be used in layers (e.g., as a marker icon).

Parameters:

Parameter Description
id The ID of the image you want to retrieve.

Returns:

Return Type Description
MapImage | void The MapImage object if found, otherwise undefined.

Ex:

let customImage = map.getImage('marker-icon-id');
if (customImage) { /* ... do something with the image ... */ }
getLayer()
getLayer(id: string): Layer | void

Returns the **layer object** from the map's style by its ID. This object contains all the properties, source, and type of the layer.

Parameters:

Parameter Description
id The ID of the layer to retrieve.

Returns:

Return Type Description
Layer | void The layer object definition if found, otherwise undefined.

Ex:

let buildingLayer = map.getLayer('3d-buildings');
console.log("Layer Type:", buildingLayer.type);
getLayersOrder()
getLayersOrder(): Array

Returns an **array of strings** representing the IDs of all layers currently in the map's style, ordered from bottom (first in the array) to top (last).

Returns:

Return Type Description
Array<string> An array of layer IDs reflecting the current draw order.

Ex:

let order = map.getLayersOrder();
console.log("Topmost Layer ID:", order[order.length - 1]);
getLayoutProperty()
getLayoutProperty(layerId: string, name: string): any

Returns the value of a specific **layout property** for a given layer. Layout properties affect the positioning and geometry of features (e.g., text-field, visibility).

Parameters:

Parameter Description
layerId The ID of the layer.
name The name of the layout property (e.g., 'visibility' or 'icon-image').

Returns:

Return Type Description
any The value of the layout property.

Ex:

let isVisible = map.getLayoutProperty('my-layer', 'visibility');
console.log("Is layer visible:", isVisible === 'visible');
getMaxBounds()
getMaxBounds(): LngLatBounds | void

Returns the **maximum geographical bounds** that the user can pan to. This is typically set during map initialization to constrain the user's view.

Returns:

Return Type Description
LngLatBounds | void The LngLatBounds object if bounds are set, otherwise undefined.

Ex:

let maxArea = map.getMaxBounds();
if (maxArea) { console.log("Max Area SW:", maxArea.getSouthWest()); }
getMaxPitch()
getMaxPitch(): number

Returns the **maximum pitch** (tilt) angle, in degrees, that the map can be set to. The default is usually 60 degrees.

Returns:

Return Type Description
number The maximum allowed pitch angle in degrees.

Ex:

let maxTilt = map.getMaxPitch();
console.log(`Maximum tilt allowed: ${maxTilt}°`);
getMaxZoom()
getMaxZoom(): number

Returns the **maximum zoom level** that can be set on the map. The default maximum is typically 22.

Returns:

Return Type Description
number The maximum allowed zoom level.

Ex:

let zoomLimit = map.getMaxZoom();
console.log(`Zoom cannot exceed: ${zoomLimit}`);
getMinPitch()
getMinPitch(): number

Returns the **minimum pitch** (tilt) angle, in degrees, that the map can be set to. The default minimum is 0 degrees (straight down view).

Returns:

Return Type Description
number The minimum allowed pitch angle in degrees.

Ex:

let minTilt = map.getMinPitch();
console.log(`Minimum tilt allowed: ${minTilt}°`);
getMinZoom()
getMinZoom(): number

Returns the **minimum zoom level** that can be set on the map. The default minimum is typically 0.

Returns:

Return Type Description
number The minimum allowed zoom level.

Ex:

let zoomFloor = map.getMinZoom();
console.log(`Zoom cannot go below: ${zoomFloor}`);
getPadding()
getPadding(): PaddingOptions

Returns the current **padding** applied to the map. Padding offsets the center of the map view from the visual center, commonly used to frame an area around UI elements.

Returns:

Return Type Description
PaddingOptions An object containing top, bottom, left, and right padding values in pixels.

Ex:

let currentPadding = map.getPadding();
console.log("Top Padding:", currentPadding.top);
getPitch()
getPitch(): number

Returns the current **pitch** (tilt) angle of the map, measured in **degrees** from the plane of the screen. A pitch of 0° means the map is viewed straight down (nadir view), and a pitch of 60° (the typical maximum) means the map is significantly tilted.

Returns:

Return Type Description
number The current map pitch in degrees. The value is typically between 0 and 60.

Ex:

let currentTilt = map.getPitch();
console.log(`Current Map Pitch: ${currentTilt}°`); // e.g., 35.5
getPixelRatio()
getPixelRatio(): number

Returns the device's **pixel ratio** (also known as device-pixel-ratio or DPR). This value determines the ratio between physical screen pixels and logical CSS pixels. It is typically 1 for standard-density screens and 2 or 3 for high-density (Retina/HiDPI) screens.

Returns:

Return Type Description
number The current pixel ratio of the map's rendering context.

Ex:

let dpr = map.getPixelRatio();
console.log(`Device Pixel Ratio: ${dpr}`); // e.g., 2 for a Retina display
getRoll()
getRoll(): number

Returns the current **roll** angle of the map, measured in **degrees**. Roll is the rotation of the map around the direction the camera is currently looking (the view direction axis). This is an advanced camera property usually set alongside pitch and bearing.

Returns:

Return Type Description
number The current map roll angle in degrees.

Ex:

let currentRoll = map.getRoll();
console.log(`Current Map Roll: ${currentRoll}°`); // e.g., 5.0
getSource()
getSource(id: string): Source | void

Returns the **source object** for a given source ID that has been added to the map's style. Sources define the data used by layers (e.g., GeoJSON, Vector, Raster tiles).

Parameters:

Parameter Description
id The ID of the source to retrieve (e.g., 'my-data-source').

Returns:

Return Type Description
Source | void The source object definition if found, otherwise undefined.

Ex:

let myDataSource = map.getSource('earthquake-data');
console.log("Source Type:", myDataSource.type); // e.g., "geojson"
getStyle()
getStyle(): Style

Returns the map's current **style object** as a raw JavaScript object. The style object contains the map's metadata, sources, layers, sprites, glyphs, and overall appearance.

Returns:

Return Type Description
Style A JavaScript object conforming to the MapLibre Style Specification that defines the map's appearance.

Ex:

let currentStyle = map.getStyle();
console.log("Style Name:", currentStyle.name);
console.log("Number of Layers:", currentStyle.layers.length);
getTerrain()
getTerrain(): TerrainSpecification | void

Returns the current **terrain specification** object from the map's style. This object defines the source and properties used for rendering 3D terrain on the map. It is only available if a terrain source has been added to the style.

Returns:

Return Type Description
TerrainSpecification | void The terrain object definition (specifying the source and exaggeration), or undefined if terrain is not currently enabled in the style.

Ex:

let currentTerrain = map.getTerrain();
if (currentTerrain) {
  console.log("Terrain Source ID:", currentTerrain.source);
  console.log("Exaggeration:", currentTerrain.exaggeration); // e.g., 1.5
}
getZoom()
getZoom(): number

Returns the current **zoom level** of the map. Zoom levels typically range from 0 (fully zoomed out, global view) up to the map's maximum zoom (usually 20 or 22).

Returns:

Return Type Description
number The current magnification level of the map using Mercator projection scaling.

Ex:

let currentZoom = map.getZoom();
console.log(`Current Zoom Level: ${currentZoom}`); // e.g., 14.2
hasImage()
hasImage(id: string): boolean

Checks if an image (icon or pattern) with the given ID has been successfully **added and loaded** into the map's style using map.addImage().

Parameters:

Parameter Description
id The ID of the image to check for existence.

Returns:

Return Type Description
boolean true if the image exists and is ready for use in the style, otherwise false.

Ex:

if (map.hasImage('custom-pin')) {
  // Safely set the icon-image property
  map.setLayoutProperty('marker-layer', 'icon-image', 'custom-pin');
}
isMoving()
isMoving(): boolean

Returns a **boolean** indicating whether the map is currently undergoing any camera transition (panning, zooming, flying, rotating, or pitching). This includes user interaction or programmatic movements.

Returns:

Return Type Description
boolean true if the map is moving, false otherwise.

Ex:

// Prevent action while a transition is in progress
if (!map.isMoving()) {
  map.flyTo({ center: newCenter });
}
isRotating()
isRotating(): boolean

Returns a **boolean** indicating whether the map is currently undergoing a **bearing** (rotation) change, either via user input (e.g., control-drag) or a programmatic function like map.rotateTo().

Returns:

Return Type Description
boolean true if the map is rotating, false otherwise.

Ex:

// Display a message only if the map is currently being rotated
if (map.isRotating()) {
  console.log("Map is rotating...");
}
isSourceLoaded()
isSourceLoaded(id: string): boolean

Checks if all necessary tiles for a specific **source** have been loaded and are ready to be rendered for the current view.

Parameters:

Parameter Description
id The ID of the source to check.

Returns:

Return Type Description
boolean true if the source's data tiles are loaded and ready, false otherwise.

Ex:

if (map.isSourceLoaded('traffic-tiles')) {
  console.log("Traffic data is available.");
}
isStyleLoaded()
isStyleLoaded(): boolean

Checks if the map's complete **style** definition (including all sources, layers, and sprites) has been parsed and loaded.

Returns:

Return Type Description
boolean true if the style is loaded, false otherwise.

Ex:

if (map.isStyleLoaded()) {
  map.addLayer(newCustomLayer);
}
isZooming()
isZooming(): boolean

Checks if the map's camera is currently undergoing a **zoom level** change (either programmatically or via user input).

Returns:

Return Type Description
boolean true if the map is zooming, false otherwise.

Ex:

if (map.isZooming()) {
  console.log("Map zoom animation in progress.");
}
loaded()
loaded(): boolean

Returns a **boolean** indicating whether the map has fully loaded its style, all initial sources, and the required tiles for the current view.

Returns:

Return Type Description
boolean true if the map has finished loading everything needed to render the current view, false otherwise.

Ex:

if (map.loaded()) {
  console.log("The map is fully rendered.");
}
jumpTo()
jumpTo(options?: CameraOptions, eventData?: any): this

Immediately **changes the map's camera properties** (center, zoom, pitch, bearing) without any animation or transition.

Parameters:

Parameter Description
options An object containing the desired camera properties (e.g., center, zoom).
eventData Optional data to be passed to any fired map events.

Ex:

map.jumpTo({ center: [-118.25, 34.05], zoom: 10 });
panBy()
panBy(offset: PointLike, options?: AnimationOptions, eventData?: any): this

Moves the map's center by a specified **pixel offset** relative to the map's current center, with an optional smooth animation.

Parameters:

Parameter Description
offset A [x, y] array or Point object representing the pixel distance to move.
options Options for the transition animation (e.g., duration, easing).

Ex:

// Pan the map 100 pixels to the right over 300ms
map.panBy([100, 0], { duration: 300 });
panTo()
panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: any): this

Moves the map's center to a specified **geographical coordinate** with a smooth, straight-line animation.

Parameters:

Parameter Description
lnglat The [longitude, latitude] coordinate to move the center to.
options Options for the transition animation (e.g., duration, easing).

Ex:

map.panTo([2.3522, 48.8566], { duration: 1000 }); // Pan to Paris
resetNorth()
resetNorth(options?: AnimationOptions, eventData?: any): this

Smoothly animates the map's **bearing (rotation)** back to **$0^\circ$ (North up)** without changing the pitch or zoom.

Parameters:

Parameter Description
options Options for the transition animation.

Ex:

map.resetNorth({ duration: 800 });
resetNorthPitch()
resetNorthPitch(options?: AnimationOptions, eventData?: any): this

Smoothly animates the map's **bearing (rotation) back to $0^\circ$ (North up)** and its **pitch (tilt) back to $0^\circ$ (straight down)**.

Parameters:

Parameter Description
options Options for the transition animation.

Ex:

map.resetNorthPitch();
rotateTo()
rotateTo(bearing: number, options?: AnimationOptions, eventData?: any): this

Rotates the map to a specific **bearing (angle)** with a smooth animation.

Parameters:

Parameter Description
bearing The desired rotation angle in degrees.
options Options for the transition animation.

Ex:

map.rotateTo(90, { duration: 1500 }); // Rotate to East
setBearing()
setBearing(bearing: number, eventData?: any): this

Immediately sets the map's **bearing (rotation)** to a specific angle without any animation.

Parameters:

Parameter Description
bearing The desired rotation angle in degrees.

Ex:

map.setBearing(180); // Set view facing South
setCenter()
setCenter(center: LngLatLike, eventData?: any): this

Immediately sets the map's **geographical centerpoint** without animation.

Parameters:

Parameter Description
center The [longitude, latitude] coordinate to set as the center.

Ex:

map.setCenter([-0.1278, 51.5074]); // London
setCenterClampedToGround()
setCenterClampedToGround(lnglat: LngLatLike, eventData?: any): this

Immediately sets the map's geographical center, ensuring that the camera target is correctly **clamped to the ground elevation** when 3D terrain is enabled.

Parameters:

Parameter Description
lnglat The [longitude, latitude] coordinate to set as the center.

Ex:

map.setCenterClampedToGround([138.7305, 35.3628]); // Mount Fuji
setCenterElevation()
setCenterElevation(elevation: number, options?: AnimationOptions, eventData?: any): this

Sets the desired **elevation** of the camera's target point (the map center) in meters. This is used when adjusting camera position relative to 3D terrain.

Parameters:

Parameter Description
elevation The elevation in meters to set for the center point.
options Options for the transition animation.

Ex:

map.setCenterElevation(500, { duration: 500 });
setPitch()
setPitch(pitch: number, eventData?: any): this

Immediately sets the map's **pitch (tilt)** angle in degrees without any animation.

Parameters:

Parameter Description
pitch The desired tilt angle in degrees (e.g., 0 to 60).

Ex:

map.setPitch(45);
setRoll()
setRoll(roll: number, eventData?: any): this

Immediately sets the map's **roll** angle in degrees (rotation around the view direction) without animation.

Parameters:

Parameter Description
roll The desired roll angle in degrees.

Ex:

map.setRoll(5);
setZoom()
setZoom(zoom: number, eventData?: any): this

Immediately sets the map's **zoom level** without any animation.

Parameters:

Parameter Description
zoom The desired zoom level (e.g., 12.5).

Ex:

map.setZoom(15);
snapToNorth()
snapToNorth(options?: AnimationOptions, eventData?: any): this

Immediately resets the map's **bearing (rotation)** to **$0^\circ$ (North up)** without animation. Equivalent to map.setBearing(0).

Parameters:

Parameter Description
options Options for the transition animation (only used if duration is specified).

Ex:

map.snapToNorth();
stop()
stop(): this

Immediately **stops any ongoing camera transitions** (pan, zoom, fly, rotate) and halts all active map rendering.

Ex:

// If a user clicks a button, stop the current animation
document.getElementById('stop-btn').onclick = () => map.stop();
zoomIn()
zoomIn(options?: AnimationOptions, eventData?: any): this

Increments the map's zoom level by 1, with an optional smooth animation.

Parameters:

Parameter Description
options Options for the transition animation.

Ex:

map.zoomIn({ duration: 300 });
zoomOut()
zoomOut(options?: AnimationOptions, eventData?: any): this

Decrements the map's zoom level by 1, with an optional smooth animation.

Parameters:

Parameter Description
options Options for the transition animation.

Ex:

map.zoomOut();
zoomTo()
zoomTo(zoom: number, options?: AnimationOptions, eventData?: any): this

Sets the map's zoom level to a specific value with an optional smooth animation.

Parameters:

Parameter Description
zoom The desired zoom level.
options Options for the transition animation.

Ex:

map.zoomTo(17, { duration: 1000 });
listens()
listens(type: string): boolean

Checks if there are any active **event listeners** currently registered for the specified event type.

Parameters:

Parameter Description
type The event type string (e.g., 'click', 'move').

Returns:

Return Type Description
boolean true if there is at least one listener for that event, false otherwise.

Ex:

if (map.listens('load')) {
  console.log("Load listener is active.");
}
listImages()
listImages(): Array

Returns a list of the **IDs of all images** (icons/patterns) that have been loaded into the map's style via map.addImage().

Returns:

Return Type Description
Array<string> An array of strings representing the IDs of the loaded images.

Ex:

let imageIDs = map.listImages();
console.log("Available Images:", imageIDs);
loadImage()
loadImage(url: string, callback: (error?: Error, image?: HTMLImageElement | ImageBitmap) => void): this

Asynchronously loads an image from a URL and calls a callback function upon completion. The resulting image can then be added to the style using map.addImage().

Parameters:

Parameter Description
url The URL of the image to load.
callback A function to execute once the image is loaded, providing an error or the image element.

Ex:

map.loadImage('images/my-icon.png', (error, image) => {
  if (error) throw error;
  map.addImage('my-icon-id', image);
});
moveLayer()
moveLayer(id: string, beforeId?: string): this

Changes the **render order** of an existing layer. The layer specified by id is moved right before the layer specified by beforeId.

Parameters:

Parameter Description
id The ID of the layer to move.
beforeId (Optional) The ID of the layer that the moved layer should precede. If omitted, the layer is moved to the top.

Ex:

// Move 'water-layer' below 'road-labels'
map.moveLayer('water-layer', 'road-labels');
removeControl()
removeControl(control: IControl): this

Removes an existing **control** (like the Zoom or Navigation control) from the map.

Parameters:

Parameter Description
control The control object instance to remove.

Ex:

let nav = new maplibregl.NavigationControl();
map.addControl(nav, 'top-left');
// Later...
map.removeControl(nav);
removeImage()
removeImage(id: string): this

Removes a previously added image (icon or pattern) from the map's style.

Parameters:

Parameter Description
id The ID of the image to remove.

Ex:

map.removeImage('my-icon-id');
removeLayer()
removeLayer(id: string): this

Removes an existing **layer** from the map's style.

Parameters:

Parameter Description
id The ID of the layer to remove.

Ex:

map.removeLayer('road-labels');
removeSource()
removeSource(id: string): this

Removes a **source** (the data definition) from the map's style. Any layers that depend on this source must be removed first.

Parameters:

Parameter Description
id The ID of the source to remove.

Ex:

map.removeSource('my-data');
removeSprite()
removeSprite(): this

Removes the currently set **sprite image** (used for default icon/pattern lookups) from the map's style. This is usually managed internally by setStyle().

Ex:

map.removeSprite();
setFilter()
setFilter(layerId: string, filter?: Array, eventData?: any): this

Dynamically sets or updates the **filter** expression applied to a specific layer, changing which features from the source are visible.

Parameters:

Parameter Description
layerId The ID of the layer to modify.
filter The new filter expression array. Pass null or undefined to clear the filter.

Ex:

// Only show features where the 'category' property is 'A'
map.setFilter('my-layer', ['==', ['get', 'category'], 'A']);
setGlobalStateProperty()
setGlobalStateProperty(property: string, value: any): this

Sets a global state property that can be accessed by expressions in layer definitions. This is an advanced feature for dynamic, map-wide styling.

Parameters:

Parameter Description
property The name of the global state property to set.
value The value to assign to the property.
setLayerZoomRange()
setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this

Sets the **minimum and maximum zoom levels** at which a layer is visible. Outside this range, the layer will be hidden.

Parameters:

Parameter Description
layerId The ID of the layer to modify.
minzoom The new minimum zoom level.
maxzoom The new maximum zoom level.

Ex:

// Only show the layer between zoom 10 and 15
map.setLayerZoomRange('my-layer', 10, 15);
setLayoutProperty()
setLayoutProperty(layerId: string, name: string, value: any, eventData?: any): this

Dynamically sets or updates a **layout property** for a specified layer (e.g., 'visibility', 'text-field'). Layout properties affect feature positioning and visibility.

Parameters:

Parameter Description
layerId The ID of the layer to modify.
name The name of the layout property (e.g., 'visibility').
value The new value for the property.

Ex:

// Hide the layer
map.setLayoutProperty('road-labels', 'visibility', 'none');
setMaxBounds()
setMaxBounds(bounds: LngLatBoundsLike | void): this

Sets the **maximum geographical bounds** that the user can pan the map to. Pass null or undefined to remove the constraint.

Parameters:

Parameter Description
bounds A bounding box array (e.g., [[lngA, latA], [lngB, latB]]) or null.

Ex:

map.setMaxBounds([[-80, 20], [-50, 50]]); // Constrain to a box
setMaxPitch()
setMaxPitch(pitch: number): this

Sets the **maximum pitch (tilt)** angle, in degrees, that the map can be set to.

Parameters:

Parameter Description
pitch The maximum allowed pitch angle in degrees.

Ex:

map.setMaxPitch(85);
setMaxZoom()
setMaxZoom(zoom: number): this

Sets the **maximum zoom level** that can be set on the map.

Parameters:

Parameter Description
zoom The maximum allowed zoom level.

Ex:

map.setMaxZoom(18);
setMinPitch()
setMinPitch(pitch: number): this

Sets the **minimum pitch (tilt)** angle, in degrees, that the map can be set to.

Parameters:

Parameter Description
pitch The minimum allowed pitch angle in degrees.

Ex:

map.setMinPitch(10);
setMinZoom()
setMinZoom(zoom: number): this

Sets the **minimum zoom level** that can be set on the map.

Parameters:

Parameter Description
zoom The minimum allowed zoom level.

Ex:

map.setMinZoom(5);
setPadding()
setPadding(padding: PaddingOptions, eventData?: any): this

Sets the **padding** (in pixels) for the map's viewport. Padding offsets the apparent center of the map, useful for framing content around UI elements.

Parameters:

Parameter Description
padding An object defining top, bottom, left, and right padding values.

Ex:

map.setPadding({ top: 50, bottom: 200, left: 10, right: 10 });
setPaintProperty()
setPaintProperty(layerId: string, name: string, value: any, eventData?: any): this

Dynamically sets or updates a **paint property** for a specified layer (e.g., 'fill-color', 'line-width'). Paint properties affect feature rendering and visual appearance.

Parameters:

Parameter Description
layerId The ID of the layer to modify.
name The name of the paint property (e.g., 'fill-color').
value The new value for the property.

Ex:

// Change the fill color of a layer
map.setPaintProperty('buildings', 'fill-color', 'red');
setPixelRatio()
setPixelRatio(pixelRatio: number): this

Manually sets the **device pixel ratio (DPR)** for rendering. Overrides the default detected value. Useful for simulating high-DPR rendering on standard displays or vice-versa.

Parameters:

Parameter Description
pixelRatio The new pixel ratio value (e.g., 1, 2, 3).
setSourceTileLodParams()
setSourceTileLodParams(id: string, params: { minzoom: number }): this

Sets Level of Detail (LOD) parameters for a specific source's tiles. Currently limited to controlling the minzoom level at which tiles are requested.

Parameters:

Parameter Description
id The ID of the source to modify.
params An object containing LOD parameters (e.g., { minzoom: 12 }).
setSprite()
setSprite(url: string | void): this

Sets the **URL** for the sprite sheet image and JSON metadata used to retrieve standard style icons and patterns. This is usually managed by setStyle().

Parameters:

Parameter Description
url The base URL for the sprite image and JSON files. Pass null to clear.
setStyle()
setStyle(style: string | Style, options?: { diff?: boolean }): this

Sets or updates the entire map's **style**. This can be a JSON object conforming to the Style Specification or a URL pointing to one.

Parameters:

Parameter Description
style The new style object or style URL.
options (Optional) An object. If { diff: true }, the map attempts to smoothly transition the style instead of reloading everything.

Ex:

map.setStyle('test://styles/test/satellite');
// Use diff mode for smoother transition
map.setStyle(newStyleObject, { diff: true });
setTerrain()
setTerrain(terrain: TerrainSpecification | void, eventData?: any): this

Sets or updates the **terrain specification** for 3D rendering. Pass null or undefined to disable 3D terrain.

Parameters:

Parameter Description
terrain The TerrainSpecification object (specifying source and exaggeration) or null.

Ex:

map.setTerrain({ source: 'terrain-rgb', exaggeration: 2.5 });
setTransformRequest()
setTransformRequest(transformRequest: Function): this

Sets a function that can modify the URL request options for loading tiles, sprites, or glyphs. Useful for adding custom headers or tokens to requests.

Parameters:

Parameter Description
transformRequest A function that takes the URL and resource type and returns a modified request object.
updateImage()
updateImage(id: string, image: MapImage | HTMLImageElement | ImageBitmap | ImageData): this

Updates the image data for an image that has already been added to the map. Useful for dynamic, animated icons without removing and re-adding the image.

Parameters:

Parameter Description
id The ID of the image to update.
image The new image data.

Ex:

// Assuming 'my-animation' is an existing image ID
map.updateImage('my-animation', newFrameImage);
queryRenderedFeatures()
queryRenderedFeatures(geometry?: PointLike | Array, parameters?: { layers?: Array, filter?: Array }): Array

Retrieves visible GeoJSON features from the **rendered map** within a specified pixel area (a point or bounding box). Only features currently drawn on the screen are checked.

Parameters:

Parameter Description
geometry (Optional) A single pixel point or a bounding box defined by two pixel points. If omitted, all visible features are returned.
parameters (Optional) An object to specify which layers to query and an additional filter to apply.

Ex:

// Get features at click point
let features = map.queryRenderedFeatures(e.point, { layers: ['building'] });
querySourceFeatures()
querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: Array }): Array

Retrieves GeoJSON features directly from a specific **source** that are currently loaded in the client. Unlike queryRenderedFeatures, this retrieves features regardless of whether they are currently visible or filtered out by a layer.

Parameters:

Parameter Description
sourceID The ID of the source to query.
parameters (Optional) An object to specify the sourceLayer (for vector tiles) and an additional filter to apply to the source data.

Ex:

// Get all features from a GeoJSON source with a specific property
let features = map.querySourceFeatures('countries', {
  filter: ['==', 'continent', 'Europe']
});
redraw()
redraw(): this

Forces the map to **redraw** a single frame immediately. Useful after manually manipulating the map's canvas or WebGL context (use sparingly).

Ex:

map.redraw();
refreshTiles()
refreshTiles(): this

Instructs the map to re-request and redraw all visible tiles. Useful if the underlying data for a tile source has changed.

Ex:

map.refreshTiles();
remove()
remove(): void

Destroys the map instance, removing its HTML container, clearing its WebGL context, and unregistering all event listeners. This cleans up memory and resources.

Ex:

// Clean up the map instance completely
map.remove();
resize()
resize(eventData?: any): this

Instructs the map to immediately check its container size and adjust the map's canvas size and camera to match. **Crucial** to call after the map container's dimensions change (e.g., window resize, opening a sidebar).

Ex:

// Use with window resize listener
window.addEventListener('resize', () => map.resize());
triggerRepaint()
triggerRepaint(): this

Requests a repaint of the map on the next available frame, similar to requestAnimationFrame. Use this for smoother, less disruptive repaints than redraw().

Ex:

// Schedule a smooth repaint
requestAnimationFrame(() => map.triggerRepaint());
getLanguage()
getLanguage(): string

Retrieves the current language setting applied to the map. This language determines how labels and textual elements are rendered on the basemap (for example, en or local language). The returned value represents the language code currently in use.

Ex:

map.getLanguage();
setLanguage()
setLanguage(language: string): void

Sets the language used for rendering labels and textual elements on the basemap. Changing the language updates map labels dynamically without requiring a full map reload. This feature is supported only on the GTS Standard and Dark basemaps. Currently supported values are en and local.

Ex:

map.setLanguage("local");
is3DEnable()
is3DEnable(): boolean

Returns whether 3D building visualization is currently enabled on the basemap. This function is supported only when the GTS Standard or Dark basemap is applied. Only buildings are rendered in 3D; all other layers remain in 2D.

Ex:

map.is3DEnable();
set3DEnable()
set3DEnable(enable: boolean): void

Enables or disables 3D building visualization on the basemap. This function works only when the GTS Standard or Dark basemap is applied. Only buildings are rendered in 3D.

Ex:

map.set3DEnable(true);
getAllPois()
getAllPois(): string[]

Returns the complete list of available Point of Interest (POI) types supported by the basemap. This function is supported only when the GTS Standard or Dark basemap is applied.

Ex:

map.getAllPois();
getPois()
getPois(): string[]

Retrieves the list of currently enabled Point of Interest (POI) types displayed on the map. This function works only when the GTS Standard or Dark basemap is applied.

Ex:

map.getPois();
setPois()
setPois(pois: string[]): void

Sets the Point of Interest (POI) types to be displayed on the map. This function is supported only when the GTS Standard or Dark basemap is applied. Only the specified POIs will be visible.

Ex:

map.setPois(["parking", "fuel"]);

Events

The Map class emits various events that developers can listen to.

on()
on(type: string, listener: Function): this
on(type: string, layerId: string, listener: Function): this

Registers a **listener function** to be called whenever an event of the specified type is fired on the map. This is the primary method for handling map events.

Parameters:

Parameter Description
type The event type string (e.g., 'click', 'moveend', 'idle').
layerId (Optional) If provided, the listener will only fire when the event originates from a feature in this specific layer.
listener The function to execute when the event occurs. It receives the event object as an argument.

Ex:

// Listen for map-wide click events
map.on('click', (e) => {
  console.log(`Map clicked at: ${e.lngLat}`);
});

// Listen for clicks specifically on the 'buildings' layer
map.on('click', 'buildings', (e) => {
  alert(`Clicked feature ID: ${e.features[0].id}`);
});
off()
off(type: string, listener: Function): this
off(type: string, layerId: string, listener: Function): this

Removes a previously registered **event listener** function. To successfully remove a listener, the event type, layerId (if used), and the **exact same function reference** must be provided.

Parameters:

Parameter Description
type The event type string (must match the type used in on()).
layerId (Optional) The ID of the layer the listener was attached to (must match).
listener The exact function reference that was originally registered with on() or once().

Ex:

function handleMove(e) { /* ... */ }
map.on('move', handleMove);

// ... later, stop listening
map.off('move', handleMove);
once()
once(type: string, listener: Function): this
once(type: string, layerId: string, listener: Function): this

Registers a **listener function** that will be called only **once** when the event of the specified type is fired. After the first execution, the listener is automatically removed.

Parameters:

Parameter Description
type The event type string.
layerId (Optional) If provided, the listener will fire once when the event originates from a feature in this specific layer.
listener The function to execute when the event occurs.

Ex:

// Execute code only after the map's style has loaded for the first time
map.once('load', () => {
  console.log("Map style is ready!");
});