Class MapMaptiler
Hierarchy (View Summary)
- MapLibreMap
- Map
Index
Constructors
Properties
Accessors
Methods
Constructors
Maptilerconstructor
Parameters
- options: MapOptions
Returns Map
Properties
boxZoom
The map's BoxZoomHandler, which implements zooming using a drag gesture with the Shift key pressed.
Find more details and examples using boxZoom in the BoxZoomHandler section.
cameraHelper
cancelPendingTileRequestsWhileZooming
The map's property which determines whether to cancel, or retain, tiles from the current viewport which are still loading but which belong to a farther (smaller) zoom level than the current one.
- If
true, when zooming in, tiles which didn't manage to load for previous zoom levels will become canceled. This might save some computing resources for slower devices, but the map details might appear more abruptly at the end of the zoom. - If
false, when zooming in, the previous zoom level(s) tiles will progressively appear, giving a smoother map details experience. However, more tiles will be rendered in a short period of time.
cooperativeGestures
The map's CooperativeGesturesHandler, which allows the user to see cooperative gesture info when user tries to zoom in/out.
Find more details and examples using cooperativeGestures in the CooperativeGesturesHandler section.
doubleClickZoom
The map's DoubleClickZoomHandler, which allows the user to zoom by double clicking.
Find more details and examples using doubleClickZoom in the DoubleClickZoomHandler section.
dragPan
The map's DragPanHandler, which implements dragging the map with a mouse or touch gesture.
Find more details and examples using dragPan in the DragPanHandler section.
dragRotate
The map's DragRotateHandler, which implements rotating the map while dragging with the right
mouse button or with the Control key pressed. Find more details and examples using dragRotate
in the DragRotateHandler section.
handlers
keyboard
The map's KeyboardHandler, which allows the user to zoom, rotate, and pan the map using keyboard
shortcuts. Find more details and examples using keyboard in the KeyboardHandler section.
painter
scrollZoom
The map's ScrollZoomHandler, which implements zooming in and out with a scroll wheel or trackpad.
Find more details and examples using scrollZoom in the ScrollZoomHandler section.
style
Readonly Maptilertelemetry
terrain
touchPitch
The map's TwoFingersTouchPitchHandler, which allows the user to pitch the map with touch gestures.
Find more details and examples using touchPitch in the TwoFingersTouchPitchHandler section.
touchZoomRotate
The map's TwoFingersTouchZoomRotateHandler, which allows the user to zoom or rotate the map with touch gestures.
Find more details and examples using touchZoomRotate in the TwoFingersTouchZoomRotateHandler section.
transform
transformCameraUpdate
A callback used to defer camera updates or apply arbitrary constraints. If specified, this Camera instance can be used as a stateless component in React etc.
transformConstrain
The map transform's callback that overrides the default constrain function.
Accessors
repaint
- get repaint(): boolean
Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance.
Returns boolean
- set repaint(value: boolean): void
Parameters
- value: boolean
Returns void
showCollisionBoxes
- get showCollisionBoxes(): boolean
Gets and sets a Boolean indicating whether the map will render boxes around all symbols in the data source, revealing which symbols were rendered or which were hidden due to collisions. This information is useful for debugging.
Returns boolean
- set showCollisionBoxes(value: boolean): void
Parameters
- value: boolean
Returns void
showOverdrawInspector
- get showOverdrawInspector(): boolean
Gets and sets a Boolean indicating whether the map should color-code each fragment to show how many times it has been shaded. White fragments have been shaded 8 or more times. Black fragments have been shaded 0 times. This information is useful for debugging.
Returns boolean
- set showOverdrawInspector(value: boolean): void
Parameters
- value: boolean
Returns void
showPadding
- get showPadding(): boolean
Gets and sets a Boolean indicating whether the map will visualize the padding offsets.
Returns boolean
- set showPadding(value: boolean): void
Parameters
- value: boolean
Returns void
showTileBoundaries
- get showTileBoundaries(): boolean
Gets and sets a Boolean indicating whether the map will render an outline around each tile and the tile ID. These tile boundaries are useful for debugging.
The uncompressed file size of the first vector source is drawn in the top left corner of each tile, next to the tile ID.
Returns boolean
- set showTileBoundaries(value: boolean): void
Parameters
- value: boolean
Returns void
version
- get version(): string
Returns the package version of the library
Returns string
Package version of the library
vertices
- get vertices(): boolean
Returns boolean
- set vertices(value: boolean): void
Parameters
- value: boolean
Returns void
Methods
addControl
Adds an IControl to the map, calling
control.onAdd(this).An ErrorEvent will be fired if the control is invalid.
Parameters
- control: IControl
The IControl to add.
Optionalposition: ControlPositionposition on the map to which the control will be added. Valid values are
'top-left','top-right','bottom-left', and'bottom-right'. Defaults to'top-right'.
Returns this
- control: IControl
addImage
- addImage(
id: string,
image:
| ImageBitmap
| StyleImageInterface
| ImageData
| HTMLImageElement
| {
data: Uint8Array<ArrayBufferLike>
| Uint8ClampedArray<ArrayBufferLike>;
height: number;
width: number;
},
options?: Partial<StyleImageMetadata>,
): thisAdd an image to the style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with
icon-image,background-pattern,fill-pattern, orline-pattern.A ErrorEvent event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image.
Parameters
- id: string
The ID of the image.
- image:
| ImageBitmap
| StyleImageInterface
| ImageData
| HTMLImageElement
| {
data: Uint8Array<ArrayBufferLike>
| Uint8ClampedArray<ArrayBufferLike>;
height: number;
width: number;
}The image as an
HTMLImageElement,ImageData,ImageBitmapor object withwidth,height, anddataproperties with the same format asImageData. Optionaloptions: Partial<StyleImageMetadata>Options object.
Returns this
Example
// If the style's sprite does not already contain an image with ID 'cat', // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'. const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png'); if (!map.hasImage('cat')) map.addImage('cat', image.data); // Add a stretchable image that can be used with `icon-text-fit` // In this example, the image is 600px wide by 400px high. const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png'); if (map.hasImage('border-image')) return; map.addImage('border-image', image.data, { content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border stretchX: [[16, 584]], // stretch everything horizontally except the 16px border stretchY: [[16, 384]], // stretch everything vertically except the 16px border });See
- Use
HTMLImageElement: Add an icon to the map - Use
ImageData: Add a generated icon to the map
- id: string
MaptileraddLayer
- addLayer(
layer:
| CustomLayerInterface
| (
LayerSpecification & { source?: string | SourceSpecification | undefined; }
),
beforeId?: string,
): thisAdds a MapLibre style layer to the map's style.
A layer defines how data from a specified source will be styled. Read more about layer types and available paint and layout properties in the MapLibre Style Specification.
Parameters
- layer:
| CustomLayerInterface
| (
LayerSpecification & { source?: string | SourceSpecification | undefined; }
)The layer to add, conforming to either the MapLibre Style Specification's layer definition or, less commonly, the CustomLayerInterface specification. The MapLibre Style Specification's layer definition is appropriate for most layers.
OptionalbeforeId: stringThe ID of an existing layer to insert the new layer before, resulting in the new layer appearing visually beneath the existing layer. If this argument is not specified, the layer will be appended to the end of the layers array and appear visually above all other layers.
Returns this
this - layer:
addSource
Adds a source to the map's style.
Events triggered:
Triggers the
source.addevent.Parameters
- id: string
The ID of the source to add. Must not conflict with existing sources.
- source: CanvasSourceSpecification | SourceSpecification
The source object, conforming to the MapLibre Style Specification's source definition or CanvasSourceSpecification.
Returns this
Example
map.addSource('my-data', { type: 'vector', url: 'https://demotiles.maplibre.org/tiles/tiles.json' });Example
map.addSource('my-data', { "type": "geojson", "data": { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-77.0323, 38.9131] }, "properties": { "title": "Mapbox DC", "marker-symbol": "monument" } } });See
GeoJSON source: Add live realtime data
- id: string
addSprite
Adds a sprite to the map's style. Fires the
styleevent.Parameters
- id: string
The ID of the sprite to add. Must not conflict with existing sprites.
- url: string
The URL to load the sprite from
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
- id: string
areTilesLoaded
calculateCameraOptionsFromCameraLngLatAltRotation
- calculateCameraOptionsFromCameraLngLatAltRotation(
cameraLngLat: LngLatLike,
cameraAlt: number,
bearing: number,
pitch: number,
roll?: number,
): CameraOptionsGiven a camera position and rotation, calculates zoom and center point and returns them as CameraOptions.
Parameters
- cameraLngLat: LngLatLike
The lng, lat of the camera to look from
- cameraAlt: number
The altitude of the camera to look from, in meters above sea level
- bearing: number
Bearing of the camera, in degrees
- pitch: number
Pitch of the camera, in degrees
Optionalroll: numberRoll of the camera, in degrees
Returns CameraOptions
the calculated camera options
Example
// Calculate options to look from camera position(1°, 0°, 1000m) with bearing = 90°, pitch = 30°, and roll = 45° const cameraLngLat = new LngLat(1, 0); const cameraAltitude = 1000; const bearing = 90; const pitch = 30; const roll = 45; const cameraOptions = map.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAltitude, bearing, pitch, roll); // Apply calculated options map.jumpTo(cameraOptions); - cameraLngLat: LngLatLike
calculateCameraOptionsFromTo
- calculateCameraOptionsFromTo(
from: LngLat,
altitudeFrom: number,
to: LngLat,
altitudeTo?: number,
): CameraOptionsGiven a camera 'from' position and a position to look at (
to), calculates zoom and camera rotation and returns them as CameraOptions.Parameters
Returns CameraOptions
the calculated camera options
Example
// Calculate options to look from (1°, 0°, 1000m) to (1°, 1°, 0m) 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);
cameraForBounds
- cameraForBounds(
bounds: LngLatBoundsLike,
options?: CameraForBoundsOptions,
): CenterZoomBearing | undefinedParameters
- bounds: LngLatBoundsLike
Calculate the center for these bounds in the viewport and use the highest zoom level up to and including Map.getMaxZoom that fits in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. Bounds will be taken in [sw, ne] order. Southwest point will always be to the left of the northeast point.
Optionaloptions: CameraForBoundsOptionsOptions object
Returns CenterZoomBearing | undefined
If map is able to fit to provided bounds, returns
center,zoom, andbearing. If map is unable to fit, method will warn and return undefined. - bounds: LngLatBoundsLike
MaptilercenterOnIpPoint
Parameters
- zoom: number | undefined
Returns Promise<void>
coveringTiles
Returns an array of
OverscaledTileIDobjects that cover the current viewport for a given tile size. This method is useful for determining which tiles are visible in the current viewport.Parameters
- options: CoveringTilesOptions
Options for calculating the covering tiles.
Returns OverscaledTileID[]
An array of
OverscaledTileIDobjects.- options: CoveringTilesOptions
MaptilerdisableHaloAnimations
Disables the animations for the halo layer.
Returns void
MaptilerdisableSpaceAnimations
Disables the animations for the space layer.
Returns void
MaptilerdisableTerrain
Disable the 3D terrain visualization
Returns void
MaptilereaseTo
Changes any combination of center, zoom, bearing, pitch, and roll, with an animated transition between old and new values.
If
options.experimental_preloadis provided, tiles along the ease path are fetched and cached before the animation begins.Parameters
- options: WithTilePreload<EaseToOptions>
OptionaleventData: object
Returns this
MaptilerenableHaloAnimations
Enables the animations for the halo layer.
Returns void
MaptilerenableSpaceAnimations
Enables the animations for the space layer.
Returns void
MaptilerenableTerrain
Enables the 3D terrain visualization
Parameters
- exaggeration: number = ...
Returns void
Maptilerexperimental_preloadTiles
Preloads a specific set of tiles identified by their
"z/x/y"tile IDs, storing them in the SDK tile cache.Parameters
- options: PreloadTilesOptions
The options for the preload.
Returns Promise<void>
A promise that resolves when the preload is complete.
- options: PreloadTilesOptions
Maptilerexperimental_preloadTilesForBounds
Preloads all tiles within a geographic bounds across a range of zoom levels, storing them in the SDK tile cache so subsequent renders are served instantly.
Parameters
- options: PreloadTilesForBoundsOptions
The options for the preload.
Returns Promise<void>
A promise that resolves when the preload is complete.
Remarks
API Key Usage: This method issues one tile request per tile per active source. Tile count grows exponentially with zoom level — a wide zoom range over a large area can trigger thousands of requests, each counting against your MapTiler Cloud API key quota. Use narrow zoom ranges and small bounds wherever possible, and monitor consumption via the
onProgresscallback.- options: PreloadTilesForBoundsOptions
Maptilerexperimental_preloadTilesForCameraPositions
- experimental_preloadTilesForCameraPositions(
options: PreloadTilesForCameraPositionsOptions,
): Promise<void>Preloads tiles visible from each of the given camera positions, storing them in the SDK tile cache so renders at those viewpoints are served instantly.
Use this method before a planned
flyToorpanToto ensure tiles along the path are ready when the animation reaches them.Parameters
- options: PreloadTilesForCameraPositionsOptions
The options for the preload.
Returns Promise<void>
A promise that resolves when the preload is complete.
- options: PreloadTilesForCameraPositionsOptions
fire
Parameters
- event: string | Event
Optionalproperties: any
Returns this
MaptilerfitBounds
- fitBounds(
bounds: LngLatBoundsLike,
options?: WithTilePreload<FitBoundsOptions>,
eventData?: object,
): thisPans and zooms the map to contain its visible area within the specified geographical bounds. This function will also reset the map's bearing to 0 if options.bearing is not specified.
If
options.experimental_preloadis provided, tiles for the target view are fetched and cached before the animation begins.Parameters
- bounds: LngLatBoundsLike
Optionaloptions: WithTilePreload<FitBoundsOptions>OptionaleventData: object
Returns this
fitScreenCoordinates
- fitScreenCoordinates(
p0: PointLike,
p1: PointLike,
bearing: number,
options?: FitBoundsOptions,
eventData?: any,
): thisPans, rotates and zooms the map to to fit the box made by points p0 and p1 once the map is rotated to the specified bearing. To zoom without rotating, pass in the current map bearing.
Triggers the following events:
movestart,move,moveend,zoomstart,zoom,zoomendandrotate.Parameters
- p0: PointLike
First point on screen, in pixel coordinates
- p1: PointLike
Second point on screen, in pixel coordinates
- bearing: number
Desired map bearing at end of animation, in degrees
Optionaloptions: FitBoundsOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
Example
let p0 = [220, 400]; let p1 = [500, 900]; map.fitScreenCoordinates(p0, p1, map.getBearing(), { padding: {top: 10, bottom:25, left: 15, right: 5} });See
Used by BoxZoomHandler
- p0: PointLike
MaptilerfitToIpBounds
Returns Promise<void>
MaptilerflyTo
Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that evokes flight. The animation seamlessly incorporates zooming and panning to help the user maintain her bearings even after traversing a great distance.
If
options.experimental_preloadis provided, tiles along the flight path are fetched and cached before the animation begins so they are ready when rendered.Parameters
- options: WithTilePreload<FlyToOptions>
OptionaleventData: object
Returns this
MaptilerforgetPersistedProjection
Forget the persisted projection - from both constructor option and result of any
map.setProjection(..., { persist: true })calls.Returns Map
getAnisotropicFilterPitch
getBearing
Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.
Returns number
The map's current bearing.
getBounds
Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
Returns LngLatBounds
The geographical bounds of the map as LngLatBounds.
MaptilergetCameraHash
Returns string
getCameraTargetElevation
Returns the elevation for the point where the camera is looking. This value corresponds to: "meters above sea level" * "exaggeration"
Returns number
The elevation.
getCanvas
getCanvasContainer
Returns the HTML element containing the map's
<canvas>element.If you want to add non-GL overlays to the map, you should append them to this element.
This is the element to which event bindings for map interactivity (such as panning and zooming) are attached. It will receive bubbled events from child elements such as the
<canvas>, but not from map controls.Returns HTMLElement
The container of the map's
<canvas>.
getCenter
getCenterClampedToGround
Returns the value of
centerClampedToGround.If true, the elevation of the center point will automatically be set to the terrain elevation (or zero if terrain is not enabled). If false, the elevation of the center point will default to sea level and will not automatically update. Defaults to true. Needs to be set to false to keep the camera above ground when pitch > 90 degrees.
Returns boolean
getCenterElevation
Returns the elevation of the map's center point.
Returns number
The elevation of the map's center point, in meters above sea level.
getContainer
Returns the map's containing HTML element.
Returns HTMLElement
The map's container.
getFeatureState
Gets the
stateof a feature. A feature'sstateis a set of user-defined key-value pairs that are assigned to a feature at runtime. Features are identified by theirfeature.idattribute, which can be any number or string.!!! note To access the values in a feature's state object for the purposes of styling the feature, use the
feature-stateexpression.Parameters
- feature: FeatureIdentifier
Feature identifier. Feature objects returned from Map.queryRenderedFeatures or event handlers can be used as feature identifiers.
Returns any
The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.
- feature: FeatureIdentifier
getFilter
Returns the filter applied to the specified style layer.
Parameters
- layerId: string
The ID of the style layer whose filter to get.
Returns void | FilterSpecification
The layer's filter.
- layerId: string
getGlobalState
getGlyphs
Returns the value of the style's glyphs URL
Returns string | null
glyphs Style's glyphs url, or
nullif glyphs are unset.
MaptilergetHalo
Returns RadialGradientLayer | undefined
getImage
Returns an image, specified by ID, currently available in the map. This includes both images from the style's original sprite and any images that have been added at runtime using Map.addImage.
Parameters
- id: string
The ID of the image.
Returns StyleImage
An image in the map with the specified ID.
- id: string
getLayer
Returns the layer with the specified ID in the map's style.
Parameters
- id: string
The ID of the layer to get.
Returns StyleLayer | undefined
The layer with the specified ID, or
undefinedif the ID corresponds to no existing layers.- id: string
getLayersOrder
getLayoutProperty
Returns the value of a layout property in the specified style layer.
Parameters
- layerId: string
The ID of the layer to get the layout property from.
- name: string
The name of the layout property to get.
Returns any
The value of the specified layout property.
- layerId: string
getLight
Returns the value of the light object.
Returns LightSpecification
light Light properties of the style.
MaptilergetMaptilerSessionId
Get the MapTiler session ID. Convenient to dispatch to externaly built component that do not directly have access to the SDK configuration but do have access to a Map instance.
Returns string
getMaxBounds
Returns the maximum geographical bounds the map is constrained to, or
nullif none set.Returns LngLatBounds | null
The map object.
getMaxPitch
Returns the map's maximum allowable pitch.
Returns number
The maxPitch
getMaxZoom
getMinPitch
Returns the map's minimum allowable pitch.
Returns number
The minPitch
getMinZoom
getPadding
Returns the current padding applied around the map viewport.
Returns PaddingOptions
The current padding around the map viewport.
getPaintProperty
Returns the value of a paint property in the specified style layer.
Parameters
- layerId: string
The ID of the layer to get the paint property from.
- name: string
The name of a paint property to get.
Returns unknown
The value of the specified paint property.
- layerId: string
getPitch
Returns the map's current pitch (tilt).
Returns number
The map's current pitch, measured in degrees away from the plane of the screen.
getPixelRatio
Returns the map's pixel ratio. Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.
Returns number
The pixel ratio.
MaptilergetPrimaryLanguage
Get the primary language
Returns LanguageInfo
MaptilergetProjection
getRenderWorldCopies
Returns the state of
renderWorldCopies. Iftrue, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set tofalse:- When the map is zoomed out far enough that a single representation of the world does not fill the map's entire container, there will be blank space beyond 180 and -180 degrees longitude.
- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level.
Returns boolean
The renderWorldCopies
getRoll
Returns the map's current roll angle.
Returns number
The map's current roll, measured in degrees about the camera boresight.
MaptilergetSdkConfig
Get the SDK config object. This is convenient to dispatch the SDK configuration to externally built layers that do not directly have access to the SDK configuration but do have access to a Map instance.
Returns SdkConfig
getSky
getSource
Returns the source with the specified ID in the map's style.
This method is often used to update a source using the instance members for the relevant source type as defined in classes that derive from Source. For example, setting the
datafor a GeoJSON source or updating theurlandcoordinatesof an image source.Type Parameters
- TSource extends Source
Parameters
- id: string
The ID of the source to get.
Returns TSource | undefined
The style source with the specified ID or
undefinedif the ID corresponds to no existing sources. The shape of the object varies by source type. A list of options for each source type is available on the MapLibre Style Specification's Sources page.
MaptilergetSpace
Returns CubemapLayer | undefined
getSprite
Returns the as-is value of the style's sprite.
Returns { id: string; url: string }[]
style's sprite list of id-url pairs
getStyle
Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style.
Returns StyleSpecification
The map's style JSON object.
getTerrain
Get the terrain-options if terrain is loaded
Returns TerrainSpecification | null
the TerrainSpecification passed to setTerrain
MaptilergetTerrainExaggeration
Get the exaggeration factor applied to the terrain
Returns number
getVerticalFieldOfView
getZoom
getZoomSnap
Returns the map's current zoom snap level.
Returns number
The map's current zoom snap level.
hasControl
Checks if a control exists on the map.
Returns boolean
true if map contains control.
hasImage
Check whether or not an image with a specific ID exists in the style. This checks both images in the style's original sprite and any images that have been added at runtime using Map.addImage.
An ErrorEvent will be fired if the image ID is missing.
Parameters
- id: string
The ID of the image.
Returns boolean
A Boolean indicating whether the image exists.
- id: string
MaptilerhasTerrain
Know if terrian is enabled or not
Returns boolean
isEasing
Returns boolean
MaptilerisGlobeProjection
Returns whether a globe projection is currently being used
Returns boolean
MaptilerisLanguageUpdated
Returns
trueis the language was ever updated, meaning changed from what is delivered in the style. Returnsfalseif language in use is the language from the style and has never been changed.Returns boolean
isMoving
isRotating
isSourceLoaded
Returns a Boolean indicating whether the source is loaded. Returns
trueif the source with the given ID in the map's style has no outstanding network requests, otherwisefalse.A ErrorEvent event will be fired if there is no source with the specified ID.
Parameters
- id: string
The ID of the source to be checked.
Returns boolean
A Boolean indicating whether the source is loaded.
- id: string
isStyleLoaded
isZooming
jumpTo
Changes any combination of center, zoom, bearing, pitch, and roll, without an animated transition. The map will retain its current values for any details not specified in
options.Triggers the following events:
movestart,move,moveend,zoomstart,zoom,zoomend,pitchstart,pitch,pitchend,rollstart,roll,rollendandrotate.Parameters
- options: JumpToOptions
Options object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- options: JumpToOptions
listens
Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type.
Parameters
- type: string
The event type
Returns boolean
trueif there is at least one registered listener for specified event type,falseotherwise- type: string
listImages
Returns an Array of strings containing the IDs of all images currently available in the map. This includes both images from the style's original sprite and any images that have been added at runtime using Map.addImage.
Returns string[]
An Array of strings containing the names of all sprites/images currently available in the map.
loaded
Returns a Boolean indicating whether the map is fully loaded.
Returns
falseif the style is not yet fully loaded, or if there has been a change to the sources or style that has not yet fully loaded.Returns boolean
A Boolean indicating whether the map is fully loaded.
loadImage
Load an image from an external URL to be used with Map.addImage. External domains must support CORS.
Parameters
- url: string
The URL of the image file. Image file must be in png, webp, or jpg format.
Returns Promise<GetResourceResponse<ImageBitmap | HTMLImageElement>>
a promise that is resolved when the image is loaded
- url: string
migrateProjection
Parameters
- newTransform: ITransform
- newCameraHelper: ICameraHelper
Returns void
MaptilermoveLayer
Moves a layer to a different z-position.
Parameters
- id: string
The ID of the layer to move.
OptionalbeforeId: stringThe ID of an existing layer to insert the new layer before. When viewing the map, the
idlayer will appear beneath thebeforeIdlayer. IfbeforeIdis omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.
Returns this
this- id: string
off
- off<T extends keyof MapLayerEventType>(
type: T,
layer: string,
listener: (ev: MapLayerEventType[T] & Object) => void,
): thisRemoves an event listener for events previously added with
{@link Map.on}.Type Parameters
- T extends keyof MapLayerEventType
Parameters
- type: T
The event type previously used to install the listener.
- layer: string
The layer ID or listener previously used to install the listener.
- listener: (ev: MapLayerEventType[T] & Object) => void
The function previously installed as a listener.
Returns this
- off<T extends keyof MapLayerEventType>(
type: T,
layers: string[],
listener: (ev: MapLayerEventType[T] & Object) => void,
): thisOverload of the
offmethod that allows to remove an event created with multiple layers. Provide the same layer IDs as toonoronce, when the listener was registered.Type Parameters
- T extends keyof MapLayerEventType
Parameters
- type: T
The type of the event.
- layers: string[]
The layer IDs previously used to install the listener.
- listener: (ev: MapLayerEventType[T] & Object) => void
The function previously installed as a listener.
Returns this
- off<T extends keyof MapEventType>(
type: T,
listener: (ev: MapEventType[T] & Object) => void,
): thisOverload of the
offmethod that allows to remove an event created without specifying a layer.Type Parameters
- T extends keyof MapEventType
Parameters
- type: T
The type of the event.
- listener: (ev: MapEventType[T] & Object) => void
The function previously installed as a listener.
Returns this
Overload of the
offmethod that allows to remove an event created without specifying a layer.Parameters
- type: string
The type of the event.
- listener: Listener
The function previously installed as a listener.
Returns this
- type: string
on
- on<T extends keyof MapLayerEventType>(
type: T,
layer: string,
listener: (ev: MapLayerEventType[T] & Object) => void,
): SubscriptionType Parameters
- T extends keyof MapLayerEventType
Parameters
- type: T
The event type to listen for. Events compatible with the optional
layerIdparameter are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. - layer: string
The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location is within a visible feature in this layer. The event will have a
featuresproperty containing an array of the matching features. Iflayeris not supplied, the event will not have afeaturesproperty. Please note that many event types are not compatible with the optionallayerparameter. - listener: (ev: MapLayerEventType[T] & Object) => void
The function to be called when the event is fired.
Returns Subscription
Event
Adds a listener for events of a specified type, optionally limited to features in a specified style layer(s). See MapEventType and MapLayerEventType for a full list of events and their description.
Event Compatible with layerIdmousedownyes mouseupyes mouseoveryes mouseoutyes mousemoveyes mouseenteryes (required) mouseleaveyes (required) clickyes dblclickyes contextmenuyes touchstartyes touchendyes touchcancelyes wheelresizeremovetouchmovemovestartmovemoveenddragstartdragdragendzoomstartzoomzoomendrotatestartrotaterotateendpitchstartpitchpitchendboxzoomstartboxzoomendboxzoomcancelwebglcontextlostwebglcontextrestoredloadrenderidleerrordatastyledatasourcedatadataloadingstyledataloadingsourcedataloadingstyleimagemissingdataabortsourcedataabortExample
// Set an event listener that will fire // when the map has finished loading map.on('load', () => { // Once the map has finished loading, // add a new layer map.addLayer({ id: 'points-of-interest', source: { type: 'vector', url: 'https://maplibre.org/maplibre-style-spec/' }, 'source-layer': 'poi_label', type: 'circle', paint: { // MapLibre Style Specification paint properties }, layout: { // MapLibre Style Specification layout properties } }); }); - on<T extends keyof MapLayerEventType>(
type: T,
layerIds: string[],
listener: (ev: MapLayerEventType[T] & Object) => void,
): SubscriptionOverload of the
onmethod that allows to listen to events specifying multiple layers.Type Parameters
- T extends keyof MapLayerEventType
Parameters
- type: T
The type of the event.
- layerIds: string[]
The array of style layer IDs.
- listener: (ev: MapLayerEventType[T] & Object) => void
The listener callback.
Returns Subscription
- on<T extends keyof MapEventType>(
type: T,
listener: (ev: MapEventType[T] & Object) => void,
): SubscriptionOverload of the
onmethod that allows to listen to events without specifying a layer.Type Parameters
- T extends keyof MapEventType
Parameters
- type: T
The type of the event.
- listener: (ev: MapEventType[T] & Object) => void
The listener callback.
Returns Subscription
Overload of the
onmethod that allows to listen to events without specifying a layer.Parameters
- type: string
The type of the event.
- listener: Listener
The listener callback.
Returns Subscription
- type: string
once
- once<T extends keyof MapLayerEventType>(
type: T,
layer: string,
listener?: (ev: MapLayerEventType[T] & Object) => void,
): Map | Promise<MapLayerEventType[T] & Object>Adds a listener that will be called only once to a specified event type, optionally limited to features in a specified style layer.
Type Parameters
- T extends keyof MapLayerEventType
Parameters
- type: T
The event type to listen for; one of
'mousedown','mouseup','click','dblclick','mousemove','mouseenter','mouseleave','mouseover','mouseout','contextmenu','touchstart','touchend', or'touchcancel'.mouseenterandmouseoverevents are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.mouseleaveandmouseoutevents are triggered when the cursor leaves a visible portion of the specified layer, or leaves the map canvas. - layer: string
The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible feature in this layer will trigger the listener. The event will have a
featuresproperty containing an array of the matching features. Optionallistener: (ev: MapLayerEventType[T] & Object) => voidThe function to be called when the event is fired.
Returns Map | Promise<MapLayerEventType[T] & Object>
thisif listener is provided, promise otherwise to allow easier usage of async/await - once<T extends keyof MapLayerEventType>(
type: T,
layerIds: string[],
listener?: (ev: MapLayerEventType[T] & Object) => void,
): Promise<any> | MapOverload of the
oncemethod that allows to listen to events specifying multiple layers.Type Parameters
- T extends keyof MapLayerEventType
Parameters
- type: T
The type of the event.
- layerIds: string[]
The array of style layer IDs.
Optionallistener: (ev: MapLayerEventType[T] & Object) => voidThe listener callback.
Returns Promise<any> | Map
- once<T extends keyof MapEventType>(
type: T,
listener?: (ev: MapEventType[T] & Object) => void,
): Promise<any> | MapOverload of the
oncemethod that allows to listen to events without specifying a layer.Type Parameters
- T extends keyof MapEventType
Parameters
- type: T
The type of the event.
Optionallistener: (ev: MapEventType[T] & Object) => voidThe listener callback.
Returns Promise<any> | Map
MaptileronLoadAsync
Awaits for this Map instance to be "loaded" and returns a Promise to the Map. If this Map instance is already loaded, the Promise is resolved directly, otherwise, it is resolved as a result of the "load" event.
Returns Promise<Map>
MaptileronLoadWithTerrainAsync
Awaits for this Map instance to be "loaded" as well as with terrain being non-null for the first time and returns a Promise to the Map. If this Map instance is already loaded with terrain, the Promise is resolved directly, otherwise, it is resolved as a result of the "loadWithTerrain" event.
Returns Promise<Map>
MaptileronReadyAsync
Awaits for this Map instance to be "ready" and returns a Promise to the Map. If this Map instance is already ready, the Promise is resolved directly, otherwise, it is resolved as a result of the "ready" event. A map instance is "ready" when all the controls that can be managed by the contructor are dealt with. This happens after the "load" event, due to the asynchronous nature of some built-in controls.
Returns Promise<Map>
panBy
Pans the map by the specified offset.
Triggers the following events:
movestartandmoveend.Parameters
- offset: PointLike
xandycoordinates by which to pan the map. Optionaloptions: EaseToOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- offset: PointLike
MaptilerpanTo
- panTo(
lnglat: LngLatLike,
options?: WithTilePreload<AnimationOptions & { pitch?: number }>,
eventData?: object,
): thisPans the map to the specified location with an animated transition.
If
options.experimental_preloadis provided, tiles along the pan path are fetched and cached before the animation begins.Parameters
- lnglat: LngLatLike
Optionaloptions: WithTilePreload<AnimationOptions & { pitch?: number }>OptionaleventData: object
Returns this
project
Returns a Point representing pixel coordinates, relative to the map's
container, that correspond to the specified geographical location.Parameters
- lnglat: LngLatLike
The geographical location to project.
Returns Point
The Point corresponding to
lnglat, relative to the map'scontainer.- lnglat: LngLatLike
queryRenderedFeatures
- queryRenderedFeatures(
geometryOrOptions?:
| QueryRenderedFeaturesOptions
| PointLike
| [PointLike, PointLike],
options?: QueryRenderedFeaturesOptions,
): MapGeoJSONFeature[]Returns an array of MapGeoJSONFeature objects representing visible features that satisfy the query parameters.
Parameters
OptionalgeometryOrOptions: QueryRenderedFeaturesOptions | PointLike | [PointLike, PointLike](optional) The geometry of the query region in pixel points within the map viewport: either a single pixel point or a pair of top-left and bottom-right pixel points describing a bounding box. The origin of the pixel points is at the top-left of the map viewport. Omitting this parameter (i.e. calling Map.queryRenderedFeatures with zero arguments, or with only a
optionsargument) is equivalent to passing a bounding box encompassing the entire map viewport. The geometryOrOptions can receive a QueryRenderedFeaturesOptions only to support a situation where the function receives only one parameter which is the options parameter.Optionaloptions: QueryRenderedFeaturesOptions(optional) Options object.
Returns MapGeoJSONFeature[]
An array of MapGeoJSONFeature objects.
The
propertiesvalue of each returned feature object contains the properties of its source feature. For GeoJSON sources, only string and numeric property values are supported (i.e.null,Array, andObjectvalues are not supported).Each feature includes top-level
layer,source, andsourceLayerproperties. Thelayerproperty is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature.Only features that are currently rendered are included. Some features will not be included, like:
- Features from layers whose
visibilityproperty is"none". - Features from layers whose zoom range excludes the current zoom level.
- Symbol features that have been hidden due to text or icon collision.
Features from all other layers are included, including features that may have no visible contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to 0.
The topmost rendered feature appears first in the returned array, and subsequent features are sorted by descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low zoom levels) are returned only once (though subject to the following caveat).
Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.
Example
Find all features at a point
let features = map.queryRenderedFeatures( [20, 35], { layers: ['my-layer-name'] } );Example
Find all features within a static bounding box
let features = map.queryRenderedFeatures( [[10, 20], [30, 50]], { layers: ['my-layer-name'] } );Example
Find all features within a bounding box around a point
let width = 10; let height = 20; let features = map.queryRenderedFeatures([ [point.x - width / 2, point.y - height / 2], [point.x + width / 2, point.y + height / 2] ], { layers: ['my-layer-name'] });
querySourceFeatures
- querySourceFeatures(
sourceId: string,
parameters?: QuerySourceFeatureOptions | null,
): GeoJSONFeature[]Returns an array of MapGeoJSONFeature objects representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
Parameters
- sourceId: string
The ID of the vector tile or GeoJSON source to query.
Optionalparameters: QuerySourceFeatureOptions | nullThe options object.
Returns GeoJSONFeature[]
An array of MapGeoJSONFeature objects.
In contrast to Map.queryRenderedFeatures, this function returns all features matching the query parameters, whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently visible viewport.
Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple times in query results. For example, suppose there is a highway running through the bounding rectangle of a query. The results of the query will be those parts of the highway that lie within the map tiles covering the bounding rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple tiles due to tile buffering.
- sourceId: string
queryTerrainElevation
Gets the elevation at a given location, in meters above sea level. Returns null if terrain is not enabled. If terrain is enabled with some exaggeration value, the value returned here will be reflective of (multiplied by) that exaggeration value. This method should be used for proper positioning of custom 3d objects, as explained here
Parameters
- lngLatLike: LngLatLike
[x,y] or LngLat coordinates of the location
Returns number | null
elevation in meters
- lngLatLike: LngLatLike
Maptilerrecreate
Recreates the map instance with the same options. Useful for WebGL context loss.
Returns void
redraw
refreshTiles
Triggers a reload of the selected tiles
Parameters
- sourceId: string
The ID of the source
OptionaltileIds: { x: number; y: number; z: number }[]An array of tile IDs to be reloaded. If not defined, all tiles will be reloaded.
Returns void
- sourceId: string
remove
Clean up and release all internal resources associated with this map.
This includes DOM elements, event bindings, web workers, and WebGL resources.
Use this method when you are done using the map and wish to ensure that it no longer consumes browser resources. Afterwards, you must not call any other methods on the map.
Returns void
removeControl
Removes the control from the map.
An ErrorEvent will be fired if the control is invalid.
Returns this
removeFeatureState
Removes the
stateof a feature, setting it back to the default behavior. If only atarget.sourceis specified, it will remove the state for all features from that source. Iftarget.idis also specified, it will remove all keys for that feature's state. Ifkeyis also specified, it removes only that key from that feature's state. Features are identified by theirfeature.idattribute, which can be any number or string.Parameters
- target: FeatureIdentifier
Identifier of where to remove state. It can be a source, a feature, or a specific key of feature. Feature objects returned from Map.queryRenderedFeatures or event handlers can be used as feature identifiers.
Optionalkey: string(optional) The key in the feature state to reset.
Returns this
Example
Reset the entire state object for all features in the
my-sourcesourcemap.removeFeatureState({ source: 'my-source' });- target: FeatureIdentifier
removeImage
Remove an image from a style. This can be an image from the style's original sprite or any images that have been added at runtime using Map.addImage.
Parameters
- id: string
The ID of the image.
Returns void
- id: string
MaptilerremoveLayer
Removes the layer with the given ID from the map's style.
An ErrorEvent will be fired if the image parameter is invald.
Parameters
- id: string
The ID of the layer to remove
Returns this
this- id: string
removeSource
removeSprite
resetNorth
Rotates the map so that north is up (0° bearing), with an animated transition.
Triggers the following events:
movestart,moveend, androtate.Parameters
Optionaloptions: AnimationOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
resetNorthPitch
Rotates and pitches the map so that north is up (0° bearing) and pitch and roll are 0°, with an animated transition.
Triggers the following events:
movestart,move,moveend,pitchstart,pitch,pitchend,rollstart,roll,rollend, androtate.Parameters
Optionaloptions: AnimationOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
resize
Resizes the map according to the dimensions of its
containerelement.Checks if the map container size changed and updates the map if it has changed. This method must be called after the map's
containeris resized programmatically or when the map is shown after being initially hidden with CSS.Triggers the following events:
movestart,move,moveend, andresize.Parameters
OptionaleventData: anyAdditional properties to be passed to
movestart,move,resize, andmoveendevents that get triggered as a result of resize. This can be useful for differentiating the source of an event (for example, user-initiated or programmatically-triggered events).OptionalconstrainTransform: boolean
Returns this
rotateTo
Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.
Triggers the following events:
movestart,moveend, androtate.Parameters
- bearing: number
The desired bearing.
Optionaloptions: EaseToOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- bearing: number
setAnisotropicFilterPitch
Sets the map's anisotropic filter pitch or reverts it to its default.
A ErrorEvent event will be fired if anisotropicFilterPitch is out of bounds.
Parameters
OptionalanisotropicFilterPitch: number | nullThe pitch above which to apply anisotropic filtering to the map's raster layers (0-180). If
nullorundefinedis provided, the function reverts to the default pitch threshold (20).
Returns this
setBearing
Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.
Equivalent to
jumpTo({bearing: bearing}).Triggers the following events:
movestart,moveend, androtate.Parameters
- bearing: number
The desired bearing.
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- bearing: number
setCenter
Sets the map's geographical centerpoint. Equivalent to
jumpTo({center: center}).Triggers the following events:
movestartandmoveend.Parameters
- center: LngLatLike
The centerpoint to set.
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- center: LngLatLike
setCenterClampedToGround
Sets the value of
centerClampedToGround.If true, the elevation of the center point will automatically be set to the terrain elevation (or zero if terrain is not enabled). If false, the elevation of the center point will default to sea level and will not automatically update. Defaults to true. Needs to be set to false to keep the camera above ground when pitch > 90 degrees.
Parameters
- centerClampedToGround: boolean
Returns void
setCenterElevation
Sets the elevation of the map's center point, in meters above sea level. Equivalent to
jumpTo({elevation: elevation}).Triggers the following events:
movestartandmoveend.Parameters
- elevation: number
The elevation to set, in meters above sea level.
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- elevation: number
setEventedParent
Bubble all events fired by this instance of Evented to this parent instance of Evented.
Parameters
Optionalparent: Evented | nullOptionaldata: any
Returns this
setFeatureState
Sets the
stateof a feature. A feature'sstateis a set of user-defined key-value pairs that are assigned to a feature at runtime. When using this method, thestateobject is merged with any existing key-value pairs in the feature's state. Features are identified by theirfeature.idattribute, which can be any number or string.This method can only be used with sources that have a
feature.idattribute. Thefeature.idattribute can be defined in three ways:- For vector or GeoJSON sources, including an
idattribute in the original data file. - For vector or GeoJSON sources, using the
promoteIdoption at the time the source is defined. - For GeoJSON sources, using the
generateIdoption to auto-assign anidbased on the feature's index in the source data. If you change feature data usingmap.getSource('some id').setData(..), you may need to re-apply state taking into account updatedidvalues.
!!! note You can use the
feature-stateexpression to access the values in a feature's state object for the purposes of styling.Parameters
- feature: FeatureIdentifier
Feature identifier. Feature objects returned from Map.queryRenderedFeatures or event handlers can be used as feature identifiers.
- state: any
A set of key-value pairs. The values should be valid JSON types.
Returns this
Example
// When the mouse moves over the `my-layer` layer, update // the feature state for the feature under the mouse map.on('mousemove', 'my-layer', (e) => { if (e.features.length > 0) { map.setFeatureState({ source: 'my-source', sourceLayer: 'my-source-layer', id: e.features[0].id, }, { hover: true }); } });- For vector or GeoJSON sources, including an
MaptilersetFilter
- setFilter(
layerId: string,
filter?: FilterSpecification | null,
options?: StyleSetterOptions,
): thisSets the filter for the specified style layer.
Filters control which features a style layer renders from its source. Any feature for which the filter expression evaluates to
truewill be rendered on the map. Those that are false will be hidden.Use
setFilterto show a subset of your source data.To clear the filter, pass
nullorundefinedas the second parameter.Parameters
- layerId: string
Optionalfilter: FilterSpecification | nullOptionaloptions: StyleSetterOptions
Returns this
setGlobalStateProperty
Sets a global state property that can be retrieved with the
global-stateexpression. If the value is null, it resets the property to its default value defined in thestatestyle property.Parameters
- propertyName: string
The name of the state property to set.
- value: any
The value of the state property to set.
Returns this
- propertyName: string
MaptilersetGlyphs
Sets the value of the style's glyphs property.
Parameters
- glyphsUrl: string | null
Glyph URL to set. Must conform to the MapLibre Style Specification.
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
this- glyphsUrl: string | null
MaptilersetHalo
Parameters
- halo: GradientDefinition
Returns void
MaptilersetHaloAnimationActive
Sets whether the halo layer should be animated in and out.
Parameters
- active: boolean
Whether the animation should be active.
Returns void
- active: boolean
MaptilersetLanguage
Define the primary language of the map. Note that not all the languages shorthands provided are available.
Parameters
- language: string | LanguageInfo
Returns void
MaptilersetLayerZoomRange
Sets the zoom extent for the specified style layer. The zoom extent includes the minimum zoom level and maximum zoom level) at which the layer will be rendered.
Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the minimum zoom level of the source layer because the data does not exist at those zoom levels. If the minimum zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style layer will not be rendered at all zoom levels in the zoom range.
Parameters
- layerId: string
- minzoom: number
- maxzoom: number
Returns this
MaptilersetLayoutProperty
Sets the value of a layout property in the specified style layer. Layout properties define how the layer is styled. Layout properties for layers of the same type are documented together. Layers of different types have different layout properties. See the MapLibre Style Specification for the complete list of layout properties.
Parameters
- layerId: string
The ID of the layer to set the layout property in.
- name: string
The name of the layout property to set.
- value: any
The value of the layout property to set. Must be of a type appropriate for the property, as defined in the MapLibre Style Specification.
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
this- layerId: string
setLight
Sets the any combination of light values.
Parameters
- light: LightSpecification
Light properties to set. Must conform to the MapLibre Style Specification.
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
- light: LightSpecification
setMaxBounds
Sets or clears the map's geographical bounds.
Pan and zoom operations are constrained within these bounds. If a pan or zoom is performed that would display regions outside these bounds, the map will instead display a position and zoom level as close as possible to the operation's request while still remaining within the bounds.
Parameters
Optionalbounds: LngLatBoundsLike | nullThe maximum bounds to set. If
nullorundefinedis provided, the function removes the map's maximum bounds.
Returns this
setMaxPitch
Sets or clears the map's maximum pitch. If the map's current pitch is higher than the new maximum, the map will pitch to the new maximum and trigger the following events:
movestart,move,moveend,pitchstart,pitch, andpitchend.A ErrorEvent event will be fired if maxPitch is out of bounds.
Parameters
OptionalmaxPitch: number | nullThe maximum pitch to set (0-180). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. If
nullorundefinedis provided, the function removes the current maximum pitch (sets it to 60).
Returns this
setMaxZoom
Sets or clears the map's maximum zoom level. If the map's current zoom level is higher than the new maximum, the map will zoom to the new maximum and trigger the following events:
movestart,move,moveend,zoomstart,zoom, andzoomend.A ErrorEvent event will be fired if minZoom is out of bounds.
Parameters
OptionalmaxZoom: number | nullThe maximum zoom level to set. If
nullorundefinedis provided, the function removes the current maximum zoom (sets it to 22).
Returns this
setMinPitch
Sets or clears the map's minimum pitch. If the map's current pitch is lower than the new minimum, the map will pitch to the new minimum and trigger the following events:
movestart,move,moveend,pitchstart,pitch, andpitchend.A ErrorEvent event will be fired if minPitch is out of bounds.
Parameters
OptionalminPitch: number | nullThe minimum pitch to set (0-180). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project. If
nullorundefinedis provided, the function removes the current minimum pitch (i.e. sets it to 0).
Returns this
setMinZoom
Sets or clears the map's minimum zoom level. If the map's current zoom level is lower than the new minimum, the map will zoom to the new minimum and trigger the following events:
movestart,move,moveend,zoomstart,zoom, andzoomend.It is not always possible to zoom out and reach the set
minZoom. Other factors such as map height may restrict zooming. For example, if the map is 512px tall it will not be possible to zoom below zoom 0 no matter what theminZoomis set to.A ErrorEvent event will be fired if minZoom is out of bounds.
Parameters
OptionalminZoom: number | nullThe minimum zoom level to set (-2 - 24). If
nullorundefinedis provided, the function removes the current minimum zoom (i.e. sets it to -2).
Returns this
setPadding
Sets the padding in pixels around the viewport.
Equivalent to
jumpTo({padding: padding}).Triggers the following events:
movestartandmoveend.Parameters
- padding: PaddingOptions
The desired padding.
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- padding: PaddingOptions
MaptilersetPaintProperty
Sets the value of a paint property in the specified style layer.
Parameters
- layerId: string
The ID of the layer to set the paint property in.
- name: string
The name of the paint property to set.
- value: any
The value of the paint property to set. Must be of a type appropriate for the property, as defined in the MapLibre Style Specification.
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
this- layerId: string
setPitch
Sets the map's pitch (tilt). Equivalent to
jumpTo({pitch: pitch}).Triggers the following events:
movestart,moveend,pitchstart, andpitchend.Parameters
- pitch: number
The pitch to set, measured in degrees away from the plane of the screen (0-60).
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- pitch: number
setPixelRatio
Sets the map's pixel ratio. This allows to override
devicePixelRatio. After this call, the canvas'widthattribute will becontainer.clientWidth * pixelRatioand its height attribute will becontainer.clientHeight * pixelRatio. Set this to null to disabledevicePixelRatiooverride. Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.Parameters
- pixelRatio: number
The pixel ratio.
Returns void
- pixelRatio: number
MaptilersetProjection
Sets the projection to one of
ProjectionTypes.Parameters
- projection: NonNullable<ProjectionTypes>
the projection type to set
Optionaloptions: ProjectionChangeOptionsconfigure behaviour of the projection change
Returns this
- projection: NonNullable<ProjectionTypes>
- setProjection(
projection: { type: NonNullable<ProjectionTypes> },
options?: ProjectionChangeOptions,
): thisSets the projection to one of
ProjectionTypes.Parameters
- projection: { type: NonNullable<ProjectionTypes> }
the projection type to set, wrapped in ProjectionSpecification
Optionaloptions: ProjectionChangeOptionsconfigure behaviour of the projection change
Returns this
- projection: { type: NonNullable<ProjectionTypes> }
Sets the projection to a
ProjectionSpecification.Parameters
- projection: ProjectionSpecification
the projection specification to set
Returns this
- projection: ProjectionSpecification
setRenderWorldCopies
Sets the state of
renderWorldCopies.Parameters
OptionalrenderWorldCopies: boolean | nullIf
true, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set tofalse:- When the map is zoomed out far enough that a single representation of the world does not fill the map's entire container, there will be blank space beyond 180 and -180 degrees longitude.
- Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the map and the other on the left edge of the map) at every zoom level.
undefinedis treated astrue,nullis treated asfalse.
Returns this
setRoll
Sets the map's roll angle. Equivalent to
jumpTo({roll: roll}).Triggers the following events:
movestart,moveend,rollstart, androllend.Parameters
- roll: number
The roll to set, measured in degrees about the camera boresight
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- roll: number
setSky
Sets the value of style's sky properties.
Parameters
- sky: SkySpecification
Sky properties to set. Must conform to the MapLibre Style Specification.
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
- sky: SkySpecification
setSourceTileLodParams
- setSourceTileLodParams(
maxZoomLevelsOnScreen: number,
tileCountMaxMinRatio: number,
sourceId?: string,
): thisChange the tile Level of Detail behavior of the specified source. These parameters have no effect when pitch == 0, and the largest effect when the horizon is visible on screen.
Parameters
- maxZoomLevelsOnScreen: number
The maximum number of distinct zoom levels allowed on screen at a time. There will generally be fewer zoom levels on the screen, the maximum can only be reached when the horizon is at the top of the screen. Increasing the maximum number of zoom levels causes the zoom level to decay faster toward the horizon.
- tileCountMaxMinRatio: number
The ratio of the maximum number of tiles loaded (at high pitch) to the minimum number of tiles loaded. Increasing this ratio allows more tiles to be loaded at high pitch angles. If the ratio would otherwise be exceeded, the zoom level is reduced uniformly to keep the number of tiles within the limit.
OptionalsourceId: stringThe ID of the source to set tile LOD parameters for. All sources will be updated if unspecified. If
sourceIdis specified but a corresponding source does not exist, an error is thrown.
Returns this
- maxZoomLevelsOnScreen: number
MaptilersetSpace
Sets the space for the map.
Parameters
- space: boolean | CubemapDefinition
the
CubemapDefinitionoptions to set. - updateOptions: boolean = true
Returns void
- space: boolean | CubemapDefinition
MaptilersetSpaceAnimationActive
Sets whether the space layer should be animated in and out.
Parameters
- active: boolean
Whether the animation should be active.
Returns void
- active: boolean
setSprite
Sets the value of the style's sprite property.
Parameters
- spriteUrl: string | null
Sprite URL to set.
Optionaloptions: StyleSetterOptionsOptions object.
Returns this
- spriteUrl: string | null
MaptilersetStyle
- setStyle(
style:
| string
| StyleSpecification
| ReferenceMapStyle
| MapStyleVariant
| StyleSpecificationWithMetaData
| null,
options?: StyleSwapOptions & StyleOptions,
): thisUpdate the style of the map. Can be:
- a full style URL (possibly with API key)
- a shorthand with only the MapTIler style name (eg.
"streets-v2") - a longer form with the prefix
"maptiler://"(eg."maptiler://streets-v2")
Parameters
- style:
| string
| StyleSpecification
| ReferenceMapStyle
| MapStyleVariant
| StyleSpecificationWithMetaData
| null Optionaloptions: StyleSwapOptions & StyleOptions
Returns this
setTerrain
Loads a 3D terrain mesh, based on a "raster-dem" source.
Triggers the
terrainevent.Parameters
- options: TerrainSpecification | null
Options object.
Returns this
- options: TerrainSpecification | null
MaptilersetTerrainAnimationDuration
Set the duration (millisec) of the terrain animation for growing or flattening. Must be positive. (Built-in default:
1000milliseconds)Parameters
- d: number
Returns void
MaptilersetTerrainExaggeration
Sets the 3D terrain exageration factor. If the terrain was not enabled prior to the call of this method, the method
.enableTerrain()will be called. Ifanimateistrue, the terrain transformation will be animated in the span of 1 second. Ifanimateisfalse, no animated transition to the newly defined exaggeration.Parameters
- exaggeration: number
- animate: boolean = true
Returns void
setTransformConstrain
Sets or clears the callback overriding how the map constrains the viewport's lnglat and zoom to respect the longitude and latitude bounds.
Parameters
Optionalconstrain: TransformConstrainFunction | nullA TransformConstrainFunction callback defining how the viewport should respect the bounds.
nullclears the callback and reverts the constrain to the map transform's default constrain function.
Returns this
MaptilersetTransformRequest
Updates the requestManager's transform request with a new function.
Parameters
- transformRequest: RequestTransformFunction
A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests. Expected to return an object with a
urlproperty and optionallyheadersandcredentialsproperties
Returns this
this- transformRequest: RequestTransformFunction
setVerticalFieldOfView
Sets the map's vertical field of view, in degrees.
Triggers the following events:
movestart,move, andmoveend.Parameters
- fov: number
The vertical field of view to set, in degrees (0-180).
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- fov: number
setZoom
Sets the map's zoom level. Equivalent to
jumpTo({zoom: zoom}).Triggers the following events:
movestart,move,moveend,zoomstart,zoom, andzoomend.Parameters
- zoom: number
The zoom level to set (0-20).
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
- zoom: number
setZoomSnap
Sets the map's zoom snap level.
Parameters
- snap: number
The zoom snap level to set.
Returns this
- snap: number
snapToNorth
Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the
bearingSnapthreshold).Triggers the following events:
movestart,moveend, androtate.Parameters
Optionaloptions: AnimationOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
stop
Stops any animated transition underway.
Returns this
triggerRepaint
Trigger the rendering of a single frame. Use this method with custom layers to repaint the map when the layer changes. Calling this multiple times before the next frame is rendered will still result in only a single frame being rendered.
Returns void
unproject
updateImage
- updateImage(
id: string,
image:
| ImageBitmap
| StyleImageInterface
| ImageData
| HTMLImageElement
| {
data: Uint8Array<ArrayBufferLike>
| Uint8ClampedArray<ArrayBufferLike>;
height: number;
width: number;
},
): thisUpdate an existing image in a style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with
icon-image,background-pattern,fill-pattern, orline-pattern.An ErrorEvent will be fired if the image parameter is invalid.
Parameters
- id: string
The ID of the image.
- image:
| ImageBitmap
| StyleImageInterface
| ImageData
| HTMLImageElement
| {
data: Uint8Array<ArrayBufferLike>
| Uint8ClampedArray<ArrayBufferLike>;
height: number;
width: number;
}The image as an
HTMLImageElement,ImageData,ImageBitmapor object withwidth,height, anddataproperties with the same format asImageData.
Returns this
- id: string
zoomIn
Incrementally increases the map's zoom level by 1, first snapping to the nearest
zoomSnapincrement.Triggers the following events:
movestart,move,moveend,zoomstart,zoom, andzoomend.Parameters
Optionaloptions: AnimationOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
zoomOut
Decreases the map's zoom level by 1, first snapping to the nearest
zoomSnapincrement.Triggers the following events:
movestart,move,moveend,zoomstart,zoom, andzoomend.Parameters
Optionaloptions: AnimationOptionsOptions object
OptionaleventData: anyAdditional properties to be added to event objects of events triggered by this method.
Returns this
MaptilerzoomTo
- zoomTo(
zoom: number,
options?: WithTilePreload<AnimationOptions> | null,
eventData?: object,
): thisZooms the map to the specified zoom level, with an animated transition.
If
options.experimental_preloadis provided, tiles for the target zoom level are fetched and cached before the animation begins.Parameters
- zoom: number
Optionaloptions: WithTilePreload<AnimationOptions> | nullOptionaleventData: object
Returns this
The Map class can be instanciated to display a map in a
<div>