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.
Constructor
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:
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
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.
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.
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.
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.
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.
Defines the initial bounds of the map. When specified, it takes
precedence over the center and zoom options provided in the
constructor.
Example:
[-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
...
});
{
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.
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.
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.
If true, the "box zoom" interaction is enabled.
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.
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].
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.
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).
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.
If set to false, the map will not attach any mouse, touch, or keyboard event listeners, meaning it will remain completely non-interactive.
Specifies the position of the gtswebsdkgl wordmark on the map. Valid values are "top-left", "top-right", "bottom-left", and "bottom-right".
If true, the gtswebsdkLogo logo will be shown.
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:
[-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
...
});
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.
The maximum pitch of the map (0-180).
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.
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.
The maximum zoom level of the map (0-24).
The minimum pitch of the map (0-180).
The minimum zoom level of the map (0-24).
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.
If set to false, the map’s pitch (tilt) control through the “drag to rotate” interaction will be disabled.
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.
If set to false, the map will not attempt to re-request tiles after they expire according to their HTTP cacheControl or expires headers.
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.
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.
If set to false, the map’s roll control through the “drag to rotate” interaction will be disabled.
If set to true, the “scroll to zoom” interaction will be enabled.
If set to true, the “drag to pitch” interaction will be enabled.
If set to true, the “pinch to rotate and zoom” interaction will be enabled.
If set to true, the map will automatically adjust its size when the browser window is resized.
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.
If set to false, style validation will be skipped. This option is useful in production environments.
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).
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.
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
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'. |
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:
type: 'vector',
url: '../tiles.json'
});
"type": "geojson",
"data": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-77.0323, 38.9131]
},
"properties": {
"title": "DC",
"marker-symbol": "monument"
}
}
});
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. |
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:
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:
OR
map.addFeatureByWkt('roads-source', [ {"geom": "LINESTRING(0 0, 10 10)", "id": 1} ], 'geom');
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:
OR
var jsonData = [ { "geom": "flexyPolyline1", "link_dir": "1196191347T" }, { "geom": "flexyPolyline2", "link_dir": "1196191348T" } ];
map.addFeatureByFlxyPolyline('travel-source', jsonData, 'geom');
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:
"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);
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:
OR
var jsonData = [ { "geom": "encodedPolyline1", "link_dir": "1196191347T" }, { "geom": "encodedPolyline2", "link_dir": "1196191348T" } ];
map.addFeatureByPolyline('travel-source', jsonData, 'geom');
Returns a Boolean indicating whether all tiles in the viewport from all sources on the style are loaded.
Ex:
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:
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);
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:
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);
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:
center:[-74.006, 40.7128],
zoom: 10,
pitch: 0,
bearing: 0,
duration: 2000,
essential: true,
padding: {
top: 50,
right: 50,
bottom: 50,
left: 50
}
});
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:
map.fitBounds(bbox, {
padding: {top: 10, bottom:25, left: 15, right: 5}
});
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 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
});
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:
center: [-122.4194, 37.7749], // San Francisco, CA
zoom: 14,
pitch: 60,
duration: 5000 // 5-second long flight
});
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:
let currentBearing = map.getBearing();
console.log(`Current Map Rotation: ${currentBearing}°`);
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:
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());
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:
let elevation = map.getCameraTargetElevation();
console.log(`Elevation at center: ${elevation} meters`); // e.g., 350.7
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:
// Use the canvas element for custom drawing or screenshot utilities let dataURL = canvasElement.toDataURL('image/png');
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:
// Apply styles or add elements to the container immediately surrounding the canvas canvasParent.style.border = '2px solid red';
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:
console.log("Longitude:", center.lng, "Latitude:", center.lat);
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:
let groundCenter = map.getCenterClampedToGround();
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:
console.log(`Elevation at map center: ${elevation}m`);
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:
// Append a custom legend div to the top-level container
mapContainer.appendChild(myLegendDiv);
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:
console.log("Current Filter:", currentFilter); // e.g., ["==", "type", "road"]
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:
if (customImage) { /* ... do something with the image ... */ }
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:
console.log("Layer Type:", buildingLayer.type);
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:
console.log("Topmost Layer ID:", order[order.length - 1]);
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:
console.log("Is layer visible:", isVisible === 'visible');
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:
if (maxArea) { console.log("Max Area SW:", maxArea.getSouthWest()); }
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:
console.log(`Maximum tilt allowed: ${maxTilt}°`);
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:
console.log(`Zoom cannot exceed: ${zoomLimit}`);
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:
console.log(`Minimum tilt allowed: ${minTilt}°`);
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:
console.log(`Zoom cannot go below: ${zoomFloor}`);
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:
console.log("Top Padding:", currentPadding.top);
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:
console.log(`Current Map Pitch: ${currentTilt}°`); // e.g., 35.5
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:
console.log(`Device Pixel Ratio: ${dpr}`); // e.g., 2 for a Retina display
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:
console.log(`Current Map Roll: ${currentRoll}°`); // e.g., 5.0
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:
console.log("Source Type:", myDataSource.type); // e.g., "geojson"
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:
console.log("Style Name:", currentStyle.name);
console.log("Number of Layers:", currentStyle.layers.length);
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:
if (currentTerrain) {
console.log("Terrain Source ID:", currentTerrain.source);
console.log("Exaggeration:", currentTerrain.exaggeration); // e.g., 1.5
}
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:
console.log(`Current Zoom Level: ${currentZoom}`); // e.g., 14.2
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:
// Safely set the icon-image property
map.setLayoutProperty('marker-layer', 'icon-image', 'custom-pin');
}
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:
if (!map.isMoving()) {
map.flyTo({ center: newCenter });
}
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:
if (map.isRotating()) {
console.log("Map is rotating...");
}
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:
console.log("Traffic data is available.");
}
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:
map.addLayer(newCustomLayer);
}
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:
console.log("Map zoom animation in progress.");
}
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:
console.log("The map is fully rendered.");
}
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:
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:
map.panBy([100, 0], { duration: 300 });
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:
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:
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:
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:
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:
Immediately sets the map's **geographical centerpoint** without animation.
Parameters:
| Parameter | Description |
|---|---|
| center | The [longitude, latitude] coordinate to set as the center. |
Ex:
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:
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:
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:
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:
Immediately sets the map's **zoom level** without any animation.
Parameters:
| Parameter | Description |
|---|---|
| zoom | The desired zoom level (e.g., 12.5). |
Ex:
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:
Immediately **stops any ongoing camera transitions** (pan, zoom, fly, rotate) and halts all active map rendering.
Ex:
document.getElementById('stop-btn').onclick = () => map.stop();
Increments the map's zoom level by 1, with an optional smooth animation.
Parameters:
| Parameter | Description |
|---|---|
| options | Options for the transition animation. |
Ex:
Decrements the map's zoom level by 1, with an optional smooth animation.
Parameters:
| Parameter | Description |
|---|---|
| options | Options for the transition animation. |
Ex:
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:
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:
console.log("Load listener is active.");
}
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:
console.log("Available Images:", imageIDs);
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:
if (error) throw error;
map.addImage('my-icon-id', image);
});
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:
map.moveLayer('water-layer', 'road-labels');
Removes an existing **control** (like the Zoom or Navigation control) from the map.
Parameters:
| Parameter | Description |
|---|---|
| control | The control object instance to remove. |
Ex:
map.addControl(nav, 'top-left');
// Later...
map.removeControl(nav);
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:
Removes an existing **layer** from the map's style.
Parameters:
| Parameter | Description |
|---|---|
| id | The ID of the layer to remove. |
Ex:
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:
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:
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:
map.setFilter('my-layer', ['==', ['get', 'category'], 'A']);
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. |
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:
map.setLayerZoomRange('my-layer', 10, 15);
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:
map.setLayoutProperty('road-labels', 'visibility', 'none');
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:
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:
Sets the **maximum zoom level** that can be set on the map.
Parameters:
| Parameter | Description |
|---|---|
| zoom | The maximum allowed zoom level. |
Ex:
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:
Sets the **minimum zoom level** that can be set on the map.
Parameters:
| Parameter | Description |
|---|---|
| zoom | The minimum allowed zoom level. |
Ex:
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:
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:
map.setPaintProperty('buildings', 'fill-color', 'red');
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). |
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 }). |
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.
|
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:
// Use diff mode for smoother transition
map.setStyle(newStyleObject, { diff: true });
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:
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. |
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:
map.updateImage('my-animation', newFrameImage);
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:
let features = map.queryRenderedFeatures(e.point, { layers: ['building'] });
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:
let features = map.querySourceFeatures('countries', {
filter: ['==', 'continent', 'Europe']
});
Forces the map to **redraw** a single frame immediately. Useful after manually manipulating the map's canvas or WebGL context (use sparingly).
Ex:
Instructs the map to re-request and redraw all visible tiles. Useful if the underlying data for a tile source has changed.
Ex:
Destroys the map instance, removing its HTML container, clearing its WebGL context, and unregistering all event listeners. This cleans up memory and resources.
Ex:
map.remove();
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:
window.addEventListener('resize', () => map.resize());
Requests a repaint of the map on the next available frame, similar to
requestAnimationFrame. Use this for smoother, less disruptive repaints than
redraw().
Ex:
requestAnimationFrame(() => map.triggerRepaint());
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:
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:
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:
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:
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:
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:
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:
Events
The Map class emits various events that developers can listen to.
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:
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}`);
});
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:
map.on('move', handleMove);
// ... later, stop listening
map.off('move', handleMove);
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:
map.once('load', () => {
console.log("Map style is ready!");
});