On this page
Constructors
Properties
Accessors
Methods
addControladdImageaddLayeraddSourceaddSpriteareTilesLoadedcalculateCameraOptionsFromCameraLngLatAltRotationcalculateCameraOptionsFromTocameraForBoundscenterOnIpPointcoveringTilesdisableHaloAnimationsdisableSpaceAnimationsdisableTerraineaseToenableHaloAnimationsenableSpaceAnimationsenableTerrainexperimental_preloadTilesexperimental_preloadTilesForBoundsexperimental_preloadTilesForCameraPositionsfirefitBoundsfitScreenCoordinatesfitToIpBoundsflyToforgetPersistedProjectiongetAnisotropicFilterPitchgetBearinggetBoundsgetCameraHashgetCameraTargetElevationgetCanvasgetCanvasContainergetCentergetCenterClampedToGroundgetCenterElevationgetContainergetFeatureStategetFiltergetGlobalStategetGlyphsgetHalogetImagegetLayergetLayersOrdergetLayoutPropertygetLightgetMaptilerSessionIdgetMaxBoundsgetMaxPitchgetMaxZoomgetMinPitchgetMinZoomgetPaddinggetPaintPropertygetPitchgetPixelRatiogetPrimaryLanguagegetProjectiongetRenderWorldCopiesgetRollgetSdkConfiggetSkygetSourcegetSpacegetSpritegetStylegetTerraingetTerrainExaggerationgetVerticalFieldOfViewgetZoomgetZoomSnaphasControlhasImagehasTerrainisEasingisGlobeProjectionisLanguageUpdatedisMovingisRotatingisSourceLoadedisStyleLoadedisZoomingjumpTolistenslistImagesloadedloadImagemigrateProjectionmoveLayeroffononceonLoadAsynconLoadWithTerrainAsynconReadyAsyncpanBypanToprojectqueryRenderedFeaturesquerySourceFeaturesqueryTerrainElevationrecreateredrawrefreshTilesremoveremoveControlremoveFeatureStateremoveImageremoveLayerremoveSourceremoveSpriteresetNorthresetNorthPitchresizerotateTosetAnisotropicFilterPitchsetBearingsetCentersetCenterClampedToGroundsetCenterElevationsetEventedParentsetFeatureStatesetFiltersetGlobalStatePropertysetGlyphssetHalosetHaloAnimationActivesetLanguagesetLayerZoomRangesetLayoutPropertysetLightsetMaxBoundssetMaxPitchsetMaxZoomsetMinPitchsetMinZoomsetPaddingsetPaintPropertysetPitchsetPixelRatiosetProjectionsetRenderWorldCopiessetRollsetSkysetSourceTileLodParamssetSpacesetSpaceAnimationActivesetSpritesetStylesetTerrainsetTerrainAnimationDurationsetTerrainExaggerationsetTransformConstrainsetTransformRequestsetVerticalFieldOfViewsetZoomsetZoomSnapsnapToNorthstoptriggerRepaintunprojectupdateImagezoomInzoomOutzoomTo

Class MapMaptiler

The Map class can be instanciated to display a map in a <div>

Hierarchy (View Summary)

Index

Constructors

Properties

Accessors

Methods

addControl addImage addLayer addSource addSprite areTilesLoaded calculateCameraOptionsFromCameraLngLatAltRotation calculateCameraOptionsFromTo cameraForBounds centerOnIpPoint coveringTiles disableHaloAnimations disableSpaceAnimations disableTerrain easeTo enableHaloAnimations enableSpaceAnimations enableTerrain experimental_preloadTiles experimental_preloadTilesForBounds experimental_preloadTilesForCameraPositions fire fitBounds fitScreenCoordinates fitToIpBounds flyTo forgetPersistedProjection getAnisotropicFilterPitch getBearing getBounds getCameraHash getCameraTargetElevation getCanvas getCanvasContainer getCenter getCenterClampedToGround getCenterElevation getContainer getFeatureState getFilter getGlobalState getGlyphs getHalo getImage getLayer getLayersOrder getLayoutProperty getLight getMaptilerSessionId getMaxBounds getMaxPitch getMaxZoom getMinPitch getMinZoom getPadding getPaintProperty getPitch getPixelRatio getPrimaryLanguage getProjection getRenderWorldCopies getRoll getSdkConfig getSky getSource getSpace getSprite getStyle getTerrain getTerrainExaggeration getVerticalFieldOfView getZoom getZoomSnap hasControl hasImage hasTerrain isEasing isGlobeProjection isLanguageUpdated isMoving isRotating isSourceLoaded isStyleLoaded isZooming jumpTo listens listImages loaded loadImage migrateProjection moveLayer off on once onLoadAsync onLoadWithTerrainAsync onReadyAsync panBy panTo project queryRenderedFeatures querySourceFeatures queryTerrainElevation recreate redraw refreshTiles remove removeControl removeFeatureState removeImage removeLayer removeSource removeSprite resetNorth resetNorthPitch resize rotateTo setAnisotropicFilterPitch setBearing setCenter setCenterClampedToGround setCenterElevation setEventedParent setFeatureState setFilter setGlobalStateProperty setGlyphs setHalo setHaloAnimationActive setLanguage setLayerZoomRange setLayoutProperty setLight setMaxBounds setMaxPitch setMaxZoom setMinPitch setMinZoom setPadding setPaintProperty setPitch setPixelRatio setProjection setRenderWorldCopies setRoll setSky setSourceTileLodParams setSpace setSpaceAnimationActive setSprite setStyle setTerrain setTerrainAnimationDuration setTerrainExaggeration setTransformConstrain setTransformRequest setVerticalFieldOfView setZoom setZoomSnap snapToNorth stop triggerRepaint unproject updateImage zoomIn zoomOut zoomTo

Constructors

Properties

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: ICameraHelper
cancelPendingTileRequestsWhileZooming: boolean

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.
true
cooperativeGestures: CooperativeGesturesHandler

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

doubleClickZoom: DoubleClickZoomHandler

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

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: DragRotateHandler

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

handlers: HandlerManager
keyboard: KeyboardHandler

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

painter: Painter
scrollZoom: ScrollZoomHandler

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

style: Style
telemetry: Telemetry
terrain: Terrain

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.

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: ITransform
transformCameraUpdate: CameraUpdateTransformFunction | null

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: TransformConstrainFunction | null

The map transform's callback that overrides the default constrain function.

null

Accessors

  • 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

  • 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

  • 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

  • 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

  • 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

    map.showTileBoundaries = true;
    
  • set showTileBoundaries(value: boolean): void

    Parameters

    • value: boolean

    Returns void

  • get version(): string

    Returns the package version of the library

    Returns string

    Package version of the library

  • get vertices(): boolean

    Returns boolean

  • set vertices(value: boolean): void

    Parameters

    • value: boolean

    Returns void

Methods

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

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

    Parameters

    Returns this

    // 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
    });
    
  • Adds a MapLibre style layer to the map's style.

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

    Parameters

    • 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: string

      The ID of an existing layer to insert the new layer before, resulting in the new layer appearing visually beneath the existing layer. If this argument is not specified, the layer will be appended to the end of the layers array and appear visually above all other layers.

    Returns this

    this

  • Adds a source to the map's style.

    Events triggered:

    Triggers the source.add event.

    Parameters

    Returns this

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

    GeoJSON source: Add live realtime data

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

    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: StyleSetterOptions

      Options object.

    Returns this

    map.addSprite('sprite-two', 'http://example.com/sprite-two');
    
  • Returns a Boolean indicating whether all tiles in the viewport from all sources on the style are loaded.

    Returns boolean

    A Boolean indicating whether all tiles are loaded.

    let tilesLoaded = map.areTilesLoaded();
    
  • Given 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: number

      Roll of the camera, in degrees

    Returns CameraOptions

    the calculated camera options

    // 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);
    
  • Given a camera 'from' position and a position to look at (to), calculates zoom and camera rotation and returns them as CameraOptions.

    Parameters

    • from: LngLat

      The camera to look from

    • altitudeFrom: number

      The altitude of the camera to look from

    • to: LngLat

      The center to look at

    • OptionalaltitudeTo: number

      Optional altitude of the center to look at. If none given the ground height will be used.

    Returns CameraOptions

    the calculated camera options

    // 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);
    
  • Parameters

    • 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: CameraForBoundsOptions

      Options object

    Returns CenterZoomBearing | undefined

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

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

    • zoom: number | undefined

    Returns Promise<void>

  • Returns an array of OverscaledTileID objects 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

    Returns OverscaledTileID[]

    An array of OverscaledTileID objects.

    // Get the tiles to cover the view for a 512x512px tile source
    const tiles = map.coveringTiles({tileSize: 512});
    
  • Disables the animations for the halo layer.

    Returns void

  • Disables the animations for the space layer.

    Returns void

  • Disable the 3D terrain visualization

    Returns void

  • Changes any combination of center, zoom, bearing, pitch, and roll, with an animated transition between old and new values.

    If options.experimental_preload is provided, tiles along the ease path are fetched and cached before the animation begins.

    Parameters

    Returns this

    API Key Usage: When experimental_preload is set, tile requests are issued for positions sampled along the ease path. These count against your MapTiler Cloud API key quota.

  • Enables the animations for the halo layer.

    Returns void

  • Enables the animations for the space layer.

    Returns void

  • Enables the 3D terrain visualization

    Parameters

    • exaggeration: number = ...

    Returns void

  • Preloads a specific set of tiles identified by their "z/x/y" tile IDs, storing them in the SDK tile cache.

    Parameters

    Returns Promise<void>

    A promise that resolves when the preload is complete.

    API Key Usage: Each tile ID results in one request per active source, counting against your MapTiler Cloud API key quota.

    await map.preloadTiles({
      tileIDs: ["12/1205/1540", "12/1206/1540"],
      onError: (err) => console.error(err),
    });
    
  • 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

    Returns Promise<void>

    A promise that resolves when the preload is complete.

    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 onProgress callback.

    await map.experimental_preloadTilesForBounds({
      bounds: map.getBounds(),
      minZoom: 8,
      maxZoom: 12,
    });
    
  • 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 flyTo or panTo to ensure tiles along the path are ready when the animation reaches them.

    Parameters

    Returns Promise<void>

    A promise that resolves when the preload is complete.

    API Key Usage: Each position triggers one request per visible tile per active source. More positions at higher zoom levels significantly increase API usage, each request counting against your MapTiler Cloud API key quota.

    await map.preloadTilesForCameraPositions({
      positions: [
        { lng: -74.006, lat: 40.7128, zoom: 12 },
        { lng: -73.935, lat: 40.730,  zoom: 14 },
      ],
      onProgress: (done, total, tileID) => console.log(tileID),
    });
    
  • Parameters

    • event: string | Event
    • Optionalproperties: any

    Returns this

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

    If options.experimental_preload is provided, tiles for the target view are fetched and cached before the animation begins.

    Parameters

    Returns this

    API Key Usage: When experimental_preload is set, tile requests are issued for the destination viewport. These count against your MapTiler Cloud API key quota.

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

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

    Parameters

    • 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: FitBoundsOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

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

    Used by BoxZoomHandler

  • Returns Promise<void>

  • 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_preload is provided, tiles along the flight path are fetched and cached before the animation begins so they are ready when rendered.

    Parameters

    Returns this

    API Key Usage: When experimental_preload is set, tile requests are issued for positions sampled along the flight path. These count against your MapTiler Cloud API key quota.

  • Forget the persisted projection - from both constructor option and result of any map.setProjection(..., { persist: true }) calls.

    Returns Map

  • Returns the map's anisotropic filter pitch. If the map is pitched beyond this threshold, anisotropic filtering will be applied to all raster layers.

    Returns number

    The anisotropicFilterPitch

    let anisotropicFilterPitch = map.getAnisotropicFilterPitch();
    
  • 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.

    let bounds = map.getBounds();
    
  • Returns string

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

    Returns number

    The elevation.

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

  • Returns the map's geographical centerpoint.

    Returns LngLat

    The map's geographical centerpoint.

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

    let center = map.getCenter();
    // access longitude and latitude values directly
    let {lng, lat} = map.getCenter();
    
  • 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

  • Returns the elevation of the map's center point.

    Returns number

    The elevation of the map's center point, in meters above sea level.

  • Returns the map's containing HTML element.

    Returns HTMLElement

    The map's container.

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

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

    Parameters

    Returns any

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

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

    map.on('mousemove', 'my-layer', (e) => {
      if (e.features.length > 0) {
        map.getFeatureState({
          source: 'my-source',
          sourceLayer: 'my-source-layer',
          id: e.features[0].id
        });
      }
    });
    
  • Returns the value of the style's glyphs URL

    Returns string | null

    glyphs Style's glyphs url, or null if glyphs are unset.

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

    let coffeeShopIcon = map.getImage("coffee_cup");
    
  • Return the ids of all layers currently in the style, including custom layers, in order.

    Returns string[]

    ids of layers, in order

    const orderedLayerIds = map.getLayersOrder();
    
  • 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.

  • 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

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

    Returns LngLatBounds | null

    The map object.

    let maxBounds = map.getMaxBounds();
    
  • Returns the map's maximum allowable pitch.

    Returns number

    The maxPitch

  • Returns the map's maximum allowable zoom level.

    Returns number

    The maxZoom

    let maxZoom = map.getMaxZoom();
    
  • Returns the map's minimum allowable pitch.

    Returns number

    The minPitch

  • Returns the map's minimum allowable zoom level.

    Returns number

    minZoom

    let minZoom = map.getMinZoom();
    
  • 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.

  • Returns the map's current pitch (tilt).

    Returns number

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

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

    Returns number

    The pixel ratio.

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

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

    Returns boolean

    The renderWorldCopies

    let worldCopiesRendered = map.getRenderWorldCopies();
    
  • Returns the map's current roll angle.

    Returns number

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

  • 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

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

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

    Type Parameters

    Parameters

    • id: string

      The ID of the source to get.

    Returns TSource | undefined

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

    let sourceObject = map.getSource('points');
    
  • Returns the as-is value of the style's sprite.

    Returns { id: string; url: string }[]

    style's sprite list of id-url pairs

  • Get the exaggeration factor applied to the terrain

    Returns number

  • Returns the map's current vertical field of view, in degrees.

    Returns number

    The map's current vertical field of view.

    36.87
    
    const verticalFieldOfView = map.getVerticalFieldOfView();
    
  • Returns the map's current zoom level.

    Returns number

    The map's current zoom level.

    map.getZoom();
    
  • Returns the map's current zoom snap level.

    Returns number

    The map's current zoom snap level.

  • Checks if a control exists on the map.

    Parameters

    Returns boolean

    true if map contains control.

    // Define a new navigation control.
    let navigation = new NavigationControl();
    // Add zoom and rotation controls to the map.
    map.addControl(navigation);
    // Check that the navigation control exists on the map.
    map.hasControl(navigation);
    
  • 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.

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

    let catIconExists = map.hasImage('cat');
    
  • Know if terrian is enabled or not

    Returns boolean

  • Returns whether a globe projection is currently being used

    Returns boolean

  • Returns true is the language was ever updated, meaning changed from what is delivered in the style. Returns false if language in use is the language from the style and has never been changed.

    Returns boolean

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

    Returns boolean

    true if the map is moving.

    let isMoving = map.isMoving();
    
  • Returns true if the map is rotating due to a camera animation or user gesture.

    Returns boolean

    true if the map is rotating.

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

    A ErrorEvent event will be fired if there is no source 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.

    let sourceLoaded = map.isSourceLoaded('bathymetry-data');
    
  • Returns a Boolean indicating whether the map's style is fully loaded.

    Returns boolean | void

    A Boolean indicating whether the style is fully loaded.

    let styleLoadStatus = map.isStyleLoaded();
    
  • Returns true if the map is zooming due to a camera animation or user gesture.

    Returns boolean

    true if the map is zooming.

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

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

    Parameters

    • options: JumpToOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    // jump to coordinates at current zoom
    map.jumpTo({center: [0, 0]});
    // jump with zoom, pitch, and bearing options
    map.jumpTo({
      center: [0, 0],
      zoom: 8,
      pitch: 45,
      bearing: 90
    });
    
  • 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

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

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

    let allImages = map.listImages();
    
  • Returns a Boolean indicating whether the map is fully loaded.

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

    Returns boolean

    A Boolean indicating whether the map is fully loaded.

  • Parameters

    Returns void

    Creates a new specialized transform instance from a projection instance and migrates to this new transform, carrying over all the properties of the old transform (center, pitch, etc.). When the style's projection is changed (or first set), this function should be called.

  • Moves a layer to a different z-position.

    Parameters

    • id: string

      The ID of the layer to move.

    • OptionalbeforeId: string

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

    Returns this

    this

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

    map.moveLayer('polygon', 'country-label');
    
  • Removes an event listener for events previously added with {@link Map.on}.

    Type Parameters

    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

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

    Type Parameters

    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

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

    Type Parameters

    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 off method 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 Parameters

    Parameters

    • type: T

      The event type to listen for. Events compatible with the optional layerId parameter are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.

    • layer: string

      The ID of a style layer or a listener if no ID is provided. Event will only be triggered if its location is within a visible feature in this layer. The event will have a features property containing an array of the matching features. If layer is not supplied, the event will not have a features property. Please note that many event types are not compatible with the optional layer parameter.

    • listener: (ev: MapLayerEventType[T] & Object) => void

      The function to be called when the event is fired.

    Returns Subscription

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

    Event Compatible with layerId
    mousedown yes
    mouseup yes
    mouseover yes
    mouseout yes
    mousemove yes
    mouseenter yes (required)
    mouseleave yes (required)
    click yes
    dblclick yes
    contextmenu yes
    touchstart yes
    touchend yes
    touchcancel yes
    wheel
    resize
    remove
    touchmove
    movestart
    move
    moveend
    dragstart
    drag
    dragend
    zoomstart
    zoom
    zoomend
    rotatestart
    rotate
    rotateend
    pitchstart
    pitch
    pitchend
    boxzoomstart
    boxzoomend
    boxzoomcancel
    webglcontextlost
    webglcontextrestored
    load
    render
    idle
    error
    data
    styledata
    sourcedata
    dataloading
    styledataloading
    sourcedataloading
    styleimagemissing
    dataabort
    sourcedataabort
    // Set an event listener that will fire
    // when the map has finished loading
    map.on('load', () => {
      // Once the map has finished loading,
      // add a new layer
      map.addLayer({
        id: 'points-of-interest',
        source: {
          type: 'vector',
          url: 'https://maplibre.org/maplibre-style-spec/'
        },
        'source-layer': 'poi_label',
        type: 'circle',
        paint: {
          // MapLibre Style Specification paint properties
        },
        layout: {
          // MapLibre Style Specification layout properties
        }
      });
    });
    
    // Set an event listener that will fire
    // when a feature on the countries layer of the map is clicked
    map.on('click', 'countries', (e) => {
      new Popup()
        .setLngLat(e.lngLat)
        .setHTML(`Country name: ${e.features[0].properties.name}`)
        .addTo(map);
    });
    
  • Overload of the on method that allows to listen to events specifying multiple layers.

    Type Parameters

    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

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

    Type Parameters

    Parameters

    • type: T

      The type of the event.

    • listener: (ev: MapEventType[T] & Object) => void

      The listener callback.

    Returns Subscription

  • Overload of the on method 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

  • 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

    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'. mouseenter and mouseover events are triggered when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas. mouseleave and mouseout events are triggered when the cursor leaves a visible portion of the specified layer, or leaves the map canvas.

    • layer: string

      The ID of a style layer or a listener if no ID is provided. Only events whose location is within a visible feature in this layer will trigger the listener. The event will have a features property containing an array of the matching features.

    • Optionallistener: (ev: MapLayerEventType[T] & Object) => void

      The function to be called when the event is fired.

    Returns Map | Promise<MapLayerEventType[T] & Object>

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

  • Overload of the once method that allows to listen to events specifying multiple layers.

    Type Parameters

    Parameters

    • type: T

      The type of the event.

    • layerIds: string[]

      The array of style layer IDs.

    • Optionallistener: (ev: MapLayerEventType[T] & Object) => void

      The listener callback.

    Returns Promise<any> | Map

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

    Type Parameters

    Parameters

    • type: T

      The type of the event.

    • Optionallistener: (ev: MapEventType[T] & Object) => void

      The listener callback.

    Returns Promise<any> | Map

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

    Parameters

    • type: string

      The type of the event.

    • Optionallistener: Listener

      The listener callback.

    Returns Promise<any> | Map

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

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

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

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

    If options.experimental_preload is provided, tiles along the pan path are fetched and cached before the animation begins.

    Parameters

    Returns this

    API Key Usage: When experimental_preload is set, tile requests are issued for positions sampled along the pan path. These count against your MapTiler Cloud API key quota.

  • 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's container.

    let coordinate = [-122.420679, 37.772537];
    let point = map.project(coordinate);
    
  • 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 options argument) is equivalent to passing a bounding box encompassing the entire map viewport. The geometryOrOptions can receive a QueryRenderedFeaturesOptions only to support a situation where the function receives only one parameter which is the options parameter.

    • Optionaloptions: QueryRenderedFeaturesOptions

      (optional) Options object.

    Returns MapGeoJSONFeature[]

    An array of MapGeoJSONFeature objects.

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

    Each feature includes top-level layer, source, and sourceLayer properties. The layer property is an object representing the style layer to which the feature belongs. Layout and paint properties in this object contain values which are fully evaluated for the given zoom level and feature.

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

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

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

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

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

    Find all features at a point

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

    Find all features within a static bounding box

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

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

    Query all rendered features from a single layer

    let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });
    
  • 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 | null

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

    Find all features in one source layer in a vector source

    let features = map.querySourceFeatures('your-source-id', {
      sourceLayer: 'your-source-layer'
    });
    
  • 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

  • Recreates the map instance with the same options. Useful for WebGL context loss.

    Returns void

  • Force a synchronous redraw of the map.

    Returns this

    map.redraw();
    
  • 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

    map.refreshTiles('satellite', [{x:1024, y: 1023, z: 11}, {x:1023, y: 1023, z: 11}]);
    
  • 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

  • Removes the control from the map.

    An ErrorEvent will be fired if the control is invalid.

    Parameters

    Returns this

    // Define a new navigation control.
    let navigation = new NavigationControl();
    // Add zoom and rotation controls to the map.
    map.addControl(navigation);
    // Remove zoom and rotation controls from the map.
    map.removeControl(navigation);
    
  • Removes the state of a feature, setting it back to the default behavior. If only a target.source is specified, it will remove the state for all features from that source. If target.id is also specified, it will remove all keys for that feature's state. If key is also specified, it removes only that key from that feature's state. Features are identified by their feature.id attribute, which can be any number or string.

    Parameters

    • 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

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

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

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

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

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

    map.on('mouseleave', 'my-layer', (e) => {
      map.removeFeatureState({
        source: 'my-source',
        sourceLayer: 'my-source-layer',
        id: e.features[0].id
      }, 'hover');
    });
    
  • 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

    // If an image with the ID 'cat' exists in
    // the style's sprite, remove it.
    if (map.hasImage('cat')) map.removeImage('cat');
    
  • 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

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

    if (map.getLayer('state-data')) map.removeLayer('state-data');
    
  • Removes a source from the map's style.

    Parameters

    • id: string

      The ID of the source to remove.

    Returns this

    map.removeSource('bathymetry-data');
    
  • Removes the sprite from the map's style. Fires the style event.

    Parameters

    • id: string

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

    Returns this

    map.removeSprite('sprite-two');
    map.removeSprite('default');
    
  • Rotates the map so that north is up (0° bearing), with an animated transition.

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

    Parameters

    • Optionaloptions: AnimationOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

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

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

    Parameters

    • Optionaloptions: AnimationOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

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

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

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

    Parameters

    • OptionaleventData: any

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

    • OptionalconstrainTransform: boolean

    Returns this

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

    let mapDiv = document.getElementById('map');
    if (mapDiv.style.visibility === true) map.resize();
    
  • Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction that is "up"; for example, a bearing of 90° orients the map so that east is up.

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

    Parameters

    • bearing: number

      The desired bearing.

    • Optionaloptions: EaseToOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

  • 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 | null

      The pitch above which to apply anisotropic filtering to the map's raster layers (0-180). If null or undefined is provided, the function reverts to the default pitch threshold (20).

    Returns this

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

    Equivalent to jumpTo({bearing: bearing}).

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

    Parameters

    • bearing: number

      The desired bearing.

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    Rotate the map to 90 degrees

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

    Triggers the following events: movestart and moveend.

    Parameters

    • center: LngLatLike

      The centerpoint to set.

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    map.setCenter([-74, 38]);
    
  • 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

  • Sets the elevation of the map's center point, in meters above sea level. Equivalent to jumpTo({elevation: elevation}).

    Triggers the following events: movestart and moveend.

    Parameters

    • elevation: number

      The elevation to set, in meters above sea level.

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

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

    Parameters

    • Optionalparent: Evented | null
    • Optionaldata: any

    Returns this

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

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

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

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

    Parameters

    • 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

    // 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
        });
      }
    });
    
  • Sets the filter for the specified style layer.

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

    Use setFilter to show a subset of your source data.

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

    Parameters

    Returns this

  • Sets a global state property that can be retrieved with the global-state expression. If the value is null, it resets the property to its default value defined in the state style property.

    Parameters

    • propertyName: string

      The name of the state property to set.

    • value: any

      The value of the state property to set.

    Returns this

  • Sets whether the halo layer should be animated in and out.

    Parameters

    • active: boolean

      Whether the animation should be active.

    Returns void

  • Define the primary language of the map. Note that not all the languages shorthands provided are available.

    Parameters

    Returns void

  • 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

  • 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: StyleSetterOptions

      Options object.

    Returns this

    this

  • 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 | null

      The maximum bounds to set. If null or undefined is provided, the function removes the map's maximum bounds.

    Returns this

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

    let bounds = [
      [-74.04728, 40.68392], // [west, south]
      [-73.91058, 40.87764]  // [east, north]
    ];
    map.setMaxBounds(bounds);
    
  • 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, and pitchend.

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

    Parameters

    • OptionalmaxPitch: number | null

      The 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 null or undefined is provided, the function removes the current maximum pitch (sets it to 60).

    Returns this

  • 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, and zoomend.

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

    Parameters

    • OptionalmaxZoom: number | null

      The maximum zoom level to set. If null or undefined is provided, the function removes the current maximum zoom (sets it to 22).

    Returns this

    map.setMaxZoom(18.75);
    
  • 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, and pitchend.

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

    Parameters

    • OptionalminPitch: number | null

      The 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 null or undefined is provided, the function removes the current minimum pitch (i.e. sets it to 0).

    Returns this

  • 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, and zoomend.

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

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

    Parameters

    • OptionalminZoom: number | null

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

    Returns this

    map.setMinZoom(12.25);
    
  • Sets the padding in pixels around the viewport.

    Equivalent to jumpTo({padding: padding}).

    Triggers the following events: movestart and moveend.

    Parameters

    • padding: PaddingOptions

      The desired padding.

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

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

    map.setPadding({ left: 300, top: 50 });
    
  • 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: StyleSetterOptions

      Options object.

    Returns this

    this

    map.setPaintProperty('my-layer', 'fill-color', '#faafee');
    
  • Sets the map's pitch (tilt). Equivalent to jumpTo({pitch: pitch}).

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

    Parameters

    • pitch: number

      The pitch to set, measured in degrees away from the plane of the screen (0-60).

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

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

    Parameters

    • pixelRatio: number

      The pixel ratio.

    Returns void

  • Sets the state of renderWorldCopies.

    Parameters

    • OptionalrenderWorldCopies: boolean | null

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

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

      undefined is treated as true, null is treated as false.

    Returns this

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

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

    Parameters

    • roll: number

      The roll to set, measured in degrees about the camera boresight

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

  • Change 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: string

      The ID of the source to set tile LOD parameters for. All sources will be updated if unspecified. If sourceId is specified but a corresponding source does not exist, an error is thrown.

    Returns this

    map.setSourceTileLodParams(4.0, 3.0, 'terrain');
    
  • Sets the space for the map.

    Parameters

    • space: boolean | CubemapDefinition

      the CubemapDefinition options to set.

    • updateOptions: boolean = true

    Returns void

    This method, at present, ** overwrites ** the current config. If an option is not set it will internally revert to the default option unless explicitly set when calling.

  • Sets whether the space layer should be animated in and out.

    Parameters

    • active: boolean

      Whether the animation should be active.

    Returns void

  • Sets the value of the style's sprite property.

    Parameters

    • spriteUrl: string | null

      Sprite URL to set.

    • Optionaloptions: StyleSetterOptions

      Options object.

    Returns this

    map.setSprite('YOUR_SPRITE_URL');
    
  • Set the duration (millisec) of the terrain animation for growing or flattening. Must be positive. (Built-in default: 1000 milliseconds)

    Parameters

    • d: number

    Returns void

  • 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. If animate is true, the terrain transformation will be animated in the span of 1 second. If animate is false, no animated transition to the newly defined exaggeration.

    Parameters

    • exaggeration: number
    • animate: boolean = true

    Returns void

  • 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 url property and optionally headers and credentials properties

    Returns this

    this

    map.setTransformRequest((url: string, resourceType: string) => {});
    
  • Sets the map's vertical field of view, in degrees.

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

    Parameters

    • fov: number

      The vertical field of view to set, in degrees (0-180).

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    36.87
    

    Change vertical field of view to 30 degrees

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

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

    Parameters

    • zoom: number

      The zoom level to set (0-20).

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    Zoom to the zoom level 5 without an animated transition

    map.setZoom(5);
    
  • Sets the map's zoom snap level.

    Parameters

    • snap: number

      The zoom snap level to set.

    Returns this

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

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

    Parameters

    • Optionaloptions: AnimationOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

  • Stops any animated transition underway.

    Returns this

  • 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

    map.triggerRepaint();
    
  • Returns a LngLat representing geographical coordinates that correspond to the specified pixel coordinates.

    Parameters

    • point: PointLike

      The pixel coordinates to unproject.

    Returns LngLat

    The LngLat corresponding to point.

    map.on('click', (e) => {
      // When the map is clicked, get the geographic coordinate.
      let coordinate = map.unproject(e.point);
    });
    
  • Update an existing image in a style. This image can be displayed on the map like any other icon in the style's sprite using the image's ID with icon-image, background-pattern, fill-pattern, or line-pattern.

    An ErrorEvent will be fired if the image parameter is 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, ImageBitmap or object with width, height, and data properties with the same format as ImageData.

    Returns this

    // If an image with the ID 'cat' already exists in the style's sprite,
    // replace that image with a new image, 'other-cat-icon.png'.
    if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');
    
  • Incrementally increases the map's zoom level by 1, first snapping to the nearest zoomSnap increment.

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

    Parameters

    • Optionaloptions: AnimationOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    Zoom the map in one level with a custom animation duration

    map.zoomIn({duration: 1000});
    
  • Decreases the map's zoom level by 1, first snapping to the nearest zoomSnap increment.

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

    Parameters

    • Optionaloptions: AnimationOptions

      Options object

    • OptionaleventData: any

      Additional properties to be added to event objects of events triggered by this method.

    Returns this

    Zoom the map out one level with a custom animation offset

    map.zoomOut({offset: [80, 60]});
    
  • Zooms the map to the specified zoom level, with an animated transition.

    If options.experimental_preload is provided, tiles for the target zoom level are fetched and cached before the animation begins.

    Parameters

    Returns this

    API Key Usage: When experimental_preload is set, tile requests are issued for the target zoom. These count against your MapTiler Cloud API key quota.

Was this helpful?
SDK JS
Reference
Map