> For the complete documentation index, see [llms.txt](https://docs.mapbox.com/mapbox-gl-js/llms.txt)

# Map

[Source Code](https://github.com/mapbox/mapbox-gl-js/blob/29a082c40985763b038163d555f9305cb39233ad/src/ui/map.ts#L460-L5354)

The `Map` object represents the map on your page. It exposes methods and properties that enable you to programmatically change the map, and fires events as users interact with it.

You create a `Map` by specifying a `container` and other options. Then Mapbox GL JS initializes the map on the page and returns your `Map` object.

Extends Camera.

> new Map class(options: <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>)

## Parameters

<table class="table table--fixed table--compact" style="width:100%;table-layout:fixed"><colgroup><col width="28%"><col></colgroup><thead><tr class="bg-gray-faint"><th style="border-top-left-radius:4px">Name</th><th style="border-top-right-radius:4px">Description</th></tr></thead><tbody><tr><td><strong>options</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span>&nbsp;</td><td><span></span></td></tr><tr><td><strong>options.accessToken</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;(default <code>null</code>)</td><td><span>If specified, map will use this <a href="https://docs.mapbox.com/help/glossary/access-token/">token</a> instead of the one defined in <code>mapboxgl.accessToken</code> .</span></td></tr><tr><td><strong>options.antialias</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>false</code>)</td><td><span>If <code>true</code> , the gl context will be created with <a href="https://en.wikipedia.org/wiki/Multisample_anti-aliasing">MSAA antialiasing</a> . This is <code>false</code> by default as a performance optimization.</span></td></tr><tr><td><strong>options.attributionControl</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , an <a href="/mapbox-gl-js/api/markers/#attributioncontrol">AttributionControl</a> will be added to the map.</span></td></tr><tr><td><strong>options.bearing</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>0</code>)</td><td><span>The initial <a href="https://docs.mapbox.com/help/glossary/camera#bearing">bearing</a> (rotation) of the map, measured in degrees counter-clockwise from north. If <code>bearing</code> is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to <code>0</code> .</span></td></tr><tr><td><strong>options.bearingSnap</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>7</code>)</td><td><span>The threshold, measured in degrees, that determines when the map's bearing will snap to north. For example, with a <code>bearingSnap</code> of 7, if the user rotates the map within 7 degrees of north, the map will automatically snap to exact north.</span></td></tr><tr><td><strong>options.bounds</strong>&nbsp;<span><a href="/mapbox-gl-js/api/geography/#lnglatboundslike">LngLatBoundsLike</a></span>&nbsp;(default <code>null</code>)</td><td><span>The initial bounds of the map. If <code>bounds</code> is specified, it overrides <code>center</code> and <code>zoom</code> constructor options.</span></td></tr><tr><td><strong>options.boxZoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "box zoom" interaction is enabled (see <a href="/mapbox-gl-js/api/handlers/#boxzoomhandler">BoxZoomHandler</a> ).</span></td></tr><tr><td><strong>options.center</strong>&nbsp;<span><a href="/mapbox-gl-js/api/geography/#lnglatlike">LngLatLike</a></span>&nbsp;(default <code>[0,0]</code>)</td><td><span>The initial geographical <a href="https://docs.mapbox.com/help/glossary/camera#center">centerpoint</a> of the map. If <code>center</code> is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to <code>[0, 0]</code> Note: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.</span></td></tr><tr><td><strong>options.clickTolerance</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>3</code>)</td><td><span>The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).</span></td></tr><tr><td><strong>options.collectResourceTiming</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>false</code>)</td><td><span>If <code>true</code> , Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a <code>resourceTiming</code> property of relevant <code>data</code> events.</span></td></tr><tr><td><strong>options.config</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span>&nbsp;(default <code>null</code>)</td><td><span>The initial configuration options for the style fragments. Each key in the object is a fragment ID (e.g., <code>basemap</code> ) and each value is a configuration object.</span></td></tr><tr><td><strong>options.container</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/HTML/Element">HTMLElement</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>)</span>&nbsp;</td><td><span>The HTML element in which Mapbox GL JS will render the map, or the element's string <code>id</code> . The specified element must have no children.</span></td></tr><tr><td><strong>options.cooperativeGestures</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a>?</span>&nbsp;</td><td><span>If <code>true</code> , scroll zoom will require pressing the ctrl or ⌘ key while scrolling to zoom map, and touch pan will require using two fingers while panning to move the map. Touch pitch will require three fingers to activate if enabled.</span></td></tr><tr><td><strong>options.crossSourceCollisions</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , symbols from multiple sources can collide with each other during collision detection. If <code>false</code> , collision detection is run separately for the symbols in each source.</span></td></tr><tr><td><strong>options.customAttribution</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a>&lt;<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>&gt;)</span>&nbsp;(default <code>null</code>)</td><td><span>String or strings to show in an <a href="/mapbox-gl-js/api/markers/#attributioncontrol">AttributionControl</a> . Only applicable if <code>options.attributionControl</code> is <code>true</code> .</span></td></tr><tr><td><strong>options.doubleClickZoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "double click to zoom" interaction is enabled (see <a href="/mapbox-gl-js/api/handlers/#doubleclickzoomhandler">DoubleClickZoomHandler</a> ).</span></td></tr><tr><td><strong>options.dragPan</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>)</span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "drag to pan" interaction is enabled. An <code>Object</code> value is passed as options to <a href="/mapbox-gl-js/api/handlers/#dragpanhandler#enable">DragPanHandler#enable</a> .</span></td></tr><tr><td><strong>options.dragRotate</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "drag to rotate" interaction is enabled (see <a href="/mapbox-gl-js/api/handlers/#dragrotatehandler">DragRotateHandler</a> ).</span></td></tr><tr><td><strong>options.fadeDuration</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>300</code>)</td><td><span>Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.</span></td></tr><tr><td><strong>options.failIfMajorPerformanceCaveat</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>false</code>)</td><td><span>If <code>true</code> , map creation will fail if the performance of Mapbox GL JS would be dramatically worse than expected (a software renderer would be used).</span></td></tr><tr><td><strong>options.fitBoundsOptions</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span>&nbsp;(default <code>null</code>)</td><td><span>A <a href="/mapbox-gl-js/api/map/#map#fitbounds">Map#fitBounds</a> options object to use <em>only</em> when fitting the initial <code>bounds</code> provided above.</span></td></tr><tr><td><strong>options.fontstackCompositing</strong>&nbsp;<span>(<code>"client"</code> | <code>"server"</code>)</span>&nbsp;(default <code>'client'</code>)</td><td><span>Controls how multi-font fontstacks are composited. When <code>'client'</code> (the default), each font in a comma-separated fontstack is loaded individually and missing glyphs are filled from subsequent fallback fonts on the client. When <code>'server'</code> , the full fontstack string is passed as-is to the glyph server, which must support server-side fontstack composition.</span></td></tr><tr><td><strong>options.hash</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>)</span>&nbsp;(default <code>false</code>)</td><td><span>If <code>true</code> , the map's <a href="https://docs.mapbox.com/help/glossary/camera">position</a> (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL. For example, <code>http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60</code> . An additional string may optionally be provided to indicate a parameter-styled hash, for example <a href="http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&amp;foo=bar">http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&amp;foo=bar</a> , where <code>foo</code> is a custom parameter and <code>bar</code> is an arbitrary hash distinct from the map hash.</span></td></tr><tr><td><strong>options.interactive</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>false</code> , no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.</span></td></tr><tr><td><strong>options.keyboard</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , keyboard shortcuts are enabled (see <a href="/mapbox-gl-js/api/handlers/#keyboardhandler">KeyboardHandler</a> ).</span></td></tr><tr><td><strong>options.language</strong>&nbsp;<span>(<code>"auto"</code> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a>&lt;<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>&gt;)</span>&nbsp;(default <code>null</code>)</td><td><span>A string with a BCP 47 language tag, or an array of such strings representing the desired languages used for the map's labels and UI components. Languages can only be set on Mapbox vector tile sources. By default, GL JS will not set a language so that the language of Mapbox tiles will be determined by the vector tile source's TileJSON. Valid language strings must be a <a href="https://en.wikipedia.org/wiki/IETF_language_tag#List_of_subtags">BCP-47 language code</a> . Unsupported BCP-47 codes will not include any translations. Invalid codes will result in an recoverable error. If a label has no translation for the selected language, it will display in the label's local language. If option is set to <code>auto</code> , GL JS will select a user's preferred language as determined by the browser's <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language"><code>window.navigator.language</code></a> property. If the <code>locale</code> property is not set separately, this language will also be used to localize the UI for supported languages.</span></td></tr><tr><td><strong>options.locale</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></span>&nbsp;(default <code>null</code>)</td><td><span>A patch to apply to the default localization table for UI strings such as control tooltips. The <code>locale</code> object maps namespaced UI string IDs to translated strings in the target language; see <a href="https://github.com/mapbox/mapbox-gl-js/blob/main/src/ui/default_locale.js"><code>src/ui/default_locale.js</code></a> for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table).</span></td></tr><tr><td><strong>options.localFontFamily</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;(default <code>null</code>)</td><td><span>Defines a CSS font-family for locally overriding generation of all glyphs. Font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). If set, this option overrides the setting in localIdeographFontFamily.</span></td></tr><tr><td><strong>options.localIdeographFontFamily</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;(default <code>'sans-serif'</code>)</td><td><span>Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana', 'Hangul Syllables' and 'CJK Symbols and Punctuation' ranges. In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). Set to <code>false</code> , to enable font settings from the map's style for these glyph ranges. Note that <a href="https://studio.mapbox.com/">Mapbox Studio</a> sets this value to <code>false</code> by default. The purpose of this option is to avoid bandwidth-intensive glyph server requests. For an example of this option in use, see <a href="https://www.mapbox.com/mapbox-gl-js/example/local-ideographs">Use locally generated ideographs</a> .</span></td></tr><tr><td><strong>options.logoPosition</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;(default <code>'bottom-left'</code>)</td><td><span>A string representing the position of the Mapbox wordmark on the map. Valid options are <code>top-left</code> , <code>top-right</code> , <code>bottom-left</code> , <code>bottom-right</code> .</span></td></tr><tr><td><strong>options.maxBounds</strong>&nbsp;<span><a href="/mapbox-gl-js/api/geography/#lnglatboundslike">LngLatBoundsLike</a></span>&nbsp;(default <code>null</code>)</td><td><span>If set, the map will be constrained to the given bounds.</span></td></tr><tr><td><strong>options.maxPitch</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>85</code>)</td><td><span>The maximum pitch of the map (0-85).</span></td></tr><tr><td><strong>options.maxTileCacheSize</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>null</code>)</td><td><span>The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport.</span></td></tr><tr><td><strong>options.maxZoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>22</code>)</td><td><span>The maximum zoom level of the map (0-24).</span></td></tr><tr><td><strong>options.minPitch</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>0</code>)</td><td><span>The minimum pitch of the map (0-85).</span></td></tr><tr><td><strong>options.minTileCacheSize</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>null</code>)</td><td><span>The minimum number of tiles stored in the tile cache for a given source. Larger viewports use more tiles and need larger caches. Larger viewports are more likely to be found on devices with more memory and on pages where the map is more important. If omitted, the cache will be dynamically sized based on the current viewport.</span></td></tr><tr><td><strong>options.minZoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>0</code>)</td><td><span>The minimum zoom level of the map (0-24).</span></td></tr><tr><td><strong>options.performanceMetricsCollection</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , mapbox-gl will collect and send performance metrics.</span></td></tr><tr><td><strong>options.pitch</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>0</code>)</td><td><span>The initial <a href="https://docs.mapbox.com/help/glossary/camera#pitch">pitch</a> (tilt) of the map, measured in degrees away from the plane of the screen (0-85). If <code>pitch</code> is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to <code>0</code> .</span></td></tr><tr><td><strong>options.pitchRotateKey</strong>&nbsp;<span>(<code>"Control"</code> | <code>"Alt"</code> | <code>"Shift"</code> | <code>"Meta"</code>)</span>&nbsp;(default <code>'Control'</code>)</td><td><span>Allows overriding the keyboard modifier key used for pitch/rotate interactions from <code>Control</code> to another modifier key.</span></td></tr><tr><td><strong>options.pitchWithRotate</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>false</code> , the map's pitch (tilt) control with "drag to rotate" interaction will be disabled.</span></td></tr><tr><td><strong>options.preserveDrawingBuffer</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>false</code>)</td><td><span>If <code>true</code> , the map's canvas can be exported to a PNG using <code>map.getCanvas().toDataURL()</code> . This is <code>false</code> by default as a performance optimization.</span></td></tr><tr><td><strong>options.projection</strong>&nbsp;<span>ProjectionSpecification</span>&nbsp;(default <code>'mercator'</code>)</td><td><span>The <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/">projection</a> the map should be rendered in. Supported projections are:<ul><li><a href="https://en.wikipedia.org/wiki/Albers_projection">Albers</a> equal-area conic projection as <code>albers</code></li><li><a href="https://en.wikipedia.org/wiki/Equal_Earth_projection">Equal Earth</a> equal-area pseudocylindrical projection as <code>equalEarth</code></li><li><a href="https://en.wikipedia.org/wiki/Equirectangular_projection">Equirectangular</a> (Plate Carrée/WGS84) as <code>equirectangular</code></li><li>3d Globe as <code>globe</code></li><li><a href="https://en.wikipedia.org/wiki/Lambert_conformal_conic_projection">Lambert Conformal Conic</a> as <code>lambertConformalConic</code></li><li><a href="https://en.wikipedia.org/wiki/Mercator_projection">Mercator</a> cylindrical map projection as <code>mercator</code></li><li><a href="https://en.wikipedia.org/wiki/Natural_Earth_projection">Natural Earth</a> pseudocylindrical map projection as <code>naturalEarth</code></li><li><a href="https://en.wikipedia.org/wiki/Winkel_tripel_projection">Winkel Tripel</a> azimuthal map projection as <code>winkelTripel</code> Conic projections such as Albers and Lambert have configurable <code>center</code> and <code>parallels</code> properties that allow developers to define the region in which the projection has minimal distortion; see the example for how to configure these properties.</li></ul></span></td></tr><tr><td><strong>options.refreshExpiredTiles</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>false</code> , the map won't attempt to re-request tiles once they expire per their HTTP <code>cacheControl</code> / <code>expires</code> headers.</span></td></tr><tr><td><strong>options.renderWorldCopies</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to <code>false</code> :<ul><li>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.</li><li>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.</li></ul></span></td></tr><tr><td><strong>options.respectPrefersReducedMotion</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If set to <code>true</code> , the map will respect the user's <code>prefers-reduced-motion</code> browser setting and apply a reduced motion mode, minimizing animations and transitions. When set to <code>false</code> , the map will always ignore the <code>prefers-reduced-motion</code> settings, regardless of the user's preference, making all animations essential.</span></td></tr><tr><td><strong>options.scaleFactor</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>1</code>)</td><td><span>The scale factor for text and icon sizes in symbol layers. A value greater than <code>1</code> increases label sizes, useful for improving accessibility or adjusting for high-density displays. The scale factor is clamped per-layer by <code>text-size-scale-range</code> and <code>icon-size-scale-range</code> style properties. This option is experimental and may change in future releases.</span></td></tr><tr><td><strong>options.scrollZoom</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>)</span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "scroll to zoom" interaction is enabled. An <code>Object</code> value is passed as options to <a href="/mapbox-gl-js/api/handlers/#scrollzoomhandler#enable">ScrollZoomHandler#enable</a> .</span></td></tr><tr><td><strong>options.style</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>)</span>&nbsp;(default <code>'mapbox://styles/mapbox/standard'</code>)</td><td><span>The map's Mapbox style. This must be an a JSON object conforming to the schema described in the <a href="https://mapbox.com/mapbox-gl-style-spec/">Mapbox Style Specification</a> , or a URL to such JSON. Can accept a null value to allow adding a style manually.<p>To load a style from the Mapbox API, you can use a URL of the form <code>mapbox://styles/:owner/:style</code>, where <code>:owner</code> is your Mapbox account name and <code>:style</code> is the style ID. You can also use a <a href="https://docs.mapbox.com/api/maps/styles/#mapbox-styles">Mapbox-owned style</a>:</p><ul><li><code>mapbox://styles/mapbox/standard</code></li><li><code>mapbox://styles/mapbox/streets-v12</code></li><li><code>mapbox://styles/mapbox/outdoors-v12</code></li><li><code>mapbox://styles/mapbox/light-v11</code></li><li><code>mapbox://styles/mapbox/dark-v11</code></li><li><code>mapbox://styles/mapbox/satellite-v9</code></li><li><code>mapbox://styles/mapbox/satellite-streets-v12</code></li><li><code>mapbox://styles/mapbox/navigation-day-v1</code></li><li><code>mapbox://styles/mapbox/navigation-night-v1</code>.</li></ul><p>Tilesets hosted with Mapbox can be style-optimized if you append <code>?optimize=true</code> to the end of your style URL, like <code>mapbox://styles/mapbox/streets-v11?optimize=true</code>. Learn more about style-optimized vector tiles in our <a href="https://www.mapbox.com/api-documentation/maps/#retrieve-tiles">API documentation</a>.</p></span></td></tr><tr><td><strong>options.testMode</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>false</code>)</td><td><span>Silences errors and warnings generated due to an invalid accessToken, useful when using the library to write unit tests.</span></td></tr><tr><td><strong>options.touchPitch</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>)</span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "drag to pitch" interaction is enabled. An <code>Object</code> value is passed as options to <a href="/mapbox-gl-js/api/handlers/#touchpitchhandler">TouchPitchHandler</a> .</span></td></tr><tr><td><strong>options.touchZoomRotate</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>)</span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the "pinch to rotate and zoom" interaction is enabled. An <code>Object</code> value is passed as options to <a href="/mapbox-gl-js/api/handlers/#touchzoomrotatehandler#enable">TouchZoomRotateHandler#enable</a> .</span></td></tr><tr><td><strong>options.trackResize</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;(default <code>true</code>)</td><td><span>If <code>true</code> , the map will automatically resize when the browser window resizes.</span></td></tr><tr><td><strong>options.transformRequest</strong>&nbsp;<span><a href="/mapbox-gl-js/api/properties/#requesttransformfunction">RequestTransformFunction</a></span>&nbsp;(default <code>null</code>)</td><td><span>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 a <a href="/mapbox-gl-js/api/properties/#requestparameters">RequestParameters</a> object with a <code>url</code> property and optionally <code>headers</code> and <code>credentials</code> properties, or a <code>Promise</code> resolving to one. Returning a <code>Promise</code> lets the callback resolve values asynchronously before each request, for example to refresh an auth token. The callback receives a third <code>options</code> argument with an optional <code>signal</code> ( <a href="AbortSignal">AbortSignal</a> ) that aborts when the request is cancelled.</span></td></tr><tr><td><strong>options.worldview</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;(default <code>null</code>)</td><td><span>Sets the map's worldview. A worldview determines the way that certain disputed boundaries are rendered. By default, GL JS will not set a worldview so that the worldview of Mapbox tiles will be determined by the vector tile source's TileJSON. Valid worldview strings must be an <a href="https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes">ISO alpha-2 country code</a> . Unsupported ISO alpha-2 codes will fall back to the TileJSON's default worldview. Invalid codes will result in a recoverable error.</span></td></tr><tr><td><strong>options.zoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a></span>&nbsp;(default <code>0</code>)</td><td><span>The initial <a href="https://docs.mapbox.com/help/glossary/camera#zoom">zoom</a> level of the map. If <code>zoom</code> is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to <code>0</code> .</span></td></tr></tbody></table>

## Example

```js
const map = new mapboxgl.Map({
    container: 'map',
    center: [-122.420679, 37.772537],
    zoom: 13,
    style: 'mapbox://styles/mapbox/standard',
    config: {
        // Initial configuration for the Mapbox Standard style set above. By default, its ID is `basemap`.
        basemap: {
            // Here, we're setting the light preset to `night`.
            lightPreset: 'night'
        }
    }
});
```

```js
const map = new mapboxgl.Map({
    container: 'map', // container ID
    center: [-122.420679, 37.772537], // starting position [lng, lat]
    zoom: 13, // starting zoom
    style: 'mapbox://styles/mapbox/streets-v11', // style URL or style object
    hash: true, // sync `center`, `zoom`, `pitch`, and `bearing` with URL
    // Use `transformRequest` to modify requests that begin with `http://myHost`.
    transformRequest: (url, resourceType) => {
        if (resourceType === 'Source' && url.startsWith('http://myHost')) {
            return {
                url: url.replace('http', 'https'),
                headers: {'my-custom-header': true},
                credentials: 'include'  // Include cookies for cross-origin requests
            };
        }
    }
});
```

```js
const map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11',
    // `transformRequest` may also be async: await a value, then return the rewritten request.
    transformRequest: async (url, resourceType, options) => {
        const token = await getFreshToken({signal: options && options.signal});
        return {url: `${url}?token=${token}`};
    }
});
```

## Instance Members

### Interaction handlers

### scrollZoom

The map's [ScrollZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#scrollzoomhandler), which implements zooming in and out with a scroll wheel or trackpad. Find more details and examples using `scrollZoom` in the [ScrollZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#scrollzoomhandler) section.

#### Type

[ScrollZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#scrollzoomhandler)

### boxZoom

The map's [BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler), which implements zooming using a drag gesture with the Shift key pressed. Find more details and examples using `boxZoom` in the [BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler) section.

#### Type

[BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler)

### dragRotate

The map's [DragRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#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](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragrotatehandler) section.

#### Type

[DragRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragrotatehandler)

### dragPan

The map's [DragPanHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragpanhandler), which implements dragging the map with a mouse or touch gesture. Find more details and examples using `dragPan` in the [DragPanHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragpanhandler) section.

#### Type

[DragPanHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragpanhandler)

### keyboard

The map's [KeyboardHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#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](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#keyboardhandler) section.

#### Type

[KeyboardHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#keyboardhandler)

### doubleClickZoom

The map's [DoubleClickZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#doubleclickzoomhandler), which allows the user to zoom by double clicking. Find more details and examples using `doubleClickZoom` in the [DoubleClickZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#doubleclickzoomhandler) section.

#### Type

[DoubleClickZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#doubleclickzoomhandler)

### touchZoomRotate

The map's [TouchZoomRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#touchzoomrotatehandler), which allows the user to zoom or rotate the map with touch gestures. Find more details and examples using `touchZoomRotate` in the [TouchZoomRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#touchzoomrotatehandler) section.

#### Type

[TouchZoomRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#touchzoomrotatehandler)

### touchPitch

The map's [TouchPitchHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#touchpitchhandler), which allows the user to pitch the map with touch gestures. Find more details and examples using `touchPitch` in the [TouchPitchHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#touchpitchhandler) section.

#### Type

[TouchPitchHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#touchpitchhandler)

### Controls

### addControl()

Adds an [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol) to the map, calling `control.onAdd(this)`.

#### Parameters

| Name | Description |
| --- | --- |
| **control** [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol)  | The [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol) to add. |
| **position** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | Position on the map to which the control will be added. Valid values are `'top-left'` , `'top'` , `'top-right'` , `'right'` , `'bottom-right'` , `'bottom'` , `'bottom-left'` , and `'left'` . Defaults to `'top-right'` . |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Add zoom and rotation controls to the map.
map.addControl(new mapboxgl.NavigationControl());
```

#### Related

-   [Example: Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)

### removeControl()

Removes the control from the map.

#### Parameters

| Name | Description |
| --- | --- |
| **control** [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol)  | The [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol) to remove. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Define a new navigation control.
const navigation = new mapboxgl.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Remove zoom and rotation controls from the map.
map.removeControl(navigation);
```

### hasControl()

Checks if a control is on the map.

#### Parameters

| Name | Description |
| --- | --- |
| **control** [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol)  | The [IControl](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/markers/#icontrol) to check. |

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): True if map contains control.

#### Example

```js
// Define a new navigation control.
const navigation = new mapboxgl.NavigationControl();
// Add zoom and rotation controls to the map.
map.addControl(navigation);
// Check that the navigation control exists on the map.
const added = map.hasControl(navigation);
// added === true
```

### getContainer()

Returns the map's containing HTML element.

#### Returns

[HTMLElement](https://developer.mozilla.org/docs/Web/HTML/Element): The map's container.

#### Example

```js
const container = map.getContainer();
```

### 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](https://developer.mozilla.org/docs/Web/HTML/Element): The container of the map's `<canvas>` .

#### Example

```js
const canvasContainer = map.getCanvasContainer();
```

#### Related

-   [Example: Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)
-   [Example: Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)

### getCanvas()

Returns the map's `<canvas>` element.

#### Returns

[HTMLCanvasElement](https://developer.mozilla.org/docs/Web/API/HTMLCanvasElement): The map's `<canvas>` element.

#### Example

```js
const canvas = map.getCanvas();
```

#### Related

-   [Example: Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)
-   [Example: Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)
-   [Example: Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)

### Map constraints

### resize()

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.

#### Parameters

| Name | Description |
| --- | --- |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be passed to `movestart` , `move` , `resize` , and `moveend` events that get triggered as a result of resize. This can be useful for differentiating the source of an event (for example, user-initiated or programmatically-triggered events). |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Resize the map when the map container is shown
// after being initially hidden with CSS.
const mapDiv = document.getElementById('map');
if (mapDiv.style.visibility === true) map.resize();
```

### 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. If a padding is set on the map, the bounds returned are for the inset. With globe projection, the smallest bounds encompassing the visible region may not precisely represent the visible region due to the earth's curvature.

#### Returns

[LngLatBounds](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatbounds): The geographical bounds of the map as [LngLatBounds](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatbounds) .

#### Example

```js
const bounds = map.getBounds();
```

### getMaxBounds()

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

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): The map object.

#### Example

```js
const maxBounds = map.getMaxBounds();
```

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

For `mercator` projection, the viewport will be constrained to the bounds. For other projections such as `globe`, only the map center will be constrained.

#### Parameters

| Name | Description |
| --- | --- |
| **bounds** ([LngLatBoundsLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatboundslike) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Define bounds that conform to the `LngLatBoundsLike` object.
const bounds = [
    [-74.04728, 40.68392], // [west, south]
    [-73.91058, 40.87764]  // [east, north]
];
// Set the map's max bounds.
map.setMaxBounds(bounds);
```

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

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.

#### Parameters

| Name | Description |
| --- | --- |
| **minZoom** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The minimum zoom level to set (-2 - 24). If `null` or `undefined` is provided, the function removes the current minimum zoom and it will be reset to -2. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setMinZoom(12.25);
```

### getMinZoom()

Returns the map's minimum allowable zoom level.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): Returns `minZoom` .

#### Example

```js
const minZoom = map.getMinZoom();
```

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

#### Parameters

| Name | Description |
| --- | --- |
| **maxZoom** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The maximum zoom level to set. If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22). |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setMaxZoom(18.75);
```

### getMaxZoom()

Returns the map's maximum allowable zoom level.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): Returns `maxZoom` .

#### Example

```js
const maxZoom = map.getMaxZoom();
```

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

#### Parameters

| Name | Description |
| --- | --- |
| **minPitch** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The minimum pitch to set (0-85). If `null` or `undefined` is provided, the function removes the current minimum pitch and resets it to 0. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setMinPitch(5);
```

### getMinPitch()

Returns the map's minimum allowable pitch.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): Returns `minPitch` .

#### Example

```js
const minPitch = map.getMinPitch();
```

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

#### Parameters

| Name | Description |
| --- | --- |
| **maxPitch** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The maximum pitch to set. If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 85). |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setMaxPitch(70);
```

### getMaxPitch()

Returns the map's maximum allowable pitch.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): Returns `maxPitch` .

#### Example

```js
const maxPitch = map.getMaxPitch();
```

### getScaleFactor()

EXPERIMENTAL

Returns the map's current scale factor for symbol sizing.

The scale factor multiplies text and icon sizes in symbol layers, useful for accessibility or adapting to different display densities. This method is experimental and may change in future releases.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current scale factor (default `1` ).

#### Example

```js
const scaleFactor = map.getScaleFactor();
```

#### Related

-   [Map#setScaleFactor](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#setscalefactor)
-   [text-size-scale-range](https://docs.mapbox.com/style-spec/reference/layers/#layout-symbol-text-size-scale-range)

### setScaleFactor()

EXPERIMENTAL

Sets the map's scale factor for symbol sizing.

The scale factor multiplies text and icon sizes in symbol layers. This is useful for improving accessibility (larger labels for users with vision impairments) or adjusting label sizes for different display densities.

The effective scale factor for each symbol layer is clamped to that layer's `text-size-scale-range` and `icon-size-scale-range` properties, allowing fine-grained control over which layers scale and by how much.

Calling this method triggers a re-layout of symbol layers whose effective scale factor changed. This method is experimental and may change in future releases.

#### Parameters

| Name | Description |
| --- | --- |
| **scaleFactor** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The scale factor to apply (default `1` ). Values greater than `1` increase sizes; values less than `1` decrease sizes. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Increase map labels for accessibility (clamped by text-size-scale-range)
map.setScaleFactor(2);
```

```js
// Reset to default size
map.setScaleFactor(1);
```

#### Related

-   [Map#getScaleFactor](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#getscalefactor)
-   [text-size-scale-range](https://docs.mapbox.com/style-spec/reference/layers/#layout-symbol-text-size-scale-range)
-   [icon-size-scale-range](https://docs.mapbox.com/style-spec/reference/layers/#layout-symbol-icon-size-scale-range)

### getRenderWorldCopies()

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](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): Returns `renderWorldCopies` boolean.

#### Example

```js
const worldCopiesRendered = map.getRenderWorldCopies();
```

#### Related

-   [Example: Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)

### setRenderWorldCopies()

Sets the state of `renderWorldCopies`.

#### Parameters

<table class="table table--fixed table--compact" style="width:100%;table-layout:fixed"><colgroup><col width="28%"><col></colgroup><thead><tr class="bg-gray-faint"><th style="border-top-left-radius:4px">Name</th><th style="border-top-right-radius:4px">Description</th></tr></thead><tbody><tr><td><strong>renderWorldCopies</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean">boolean</a></span>&nbsp;</td><td><span>If <code>true</code> , multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to <code>false</code> :<ul><li>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.</li><li>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.</li></ul><p><code>undefined</code> is treated as <code>true</code>, <code>null</code> is treated as <code>false</code>.</p></span></td></tr></tbody></table>

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setRenderWorldCopies(true);
```

#### Related

-   [Example: Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)

### getLanguage()

Returns the map's language, which is used for translating map labels and UI components.

#### Returns

([undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>): Returns the map's language code.

#### Example

```js
const language = map.getLanguage();
```

### setLanguage()

Sets the map's language, which is used for translating map labels and UI components.

#### Parameters

| Name | Description |
| --- | --- |
| **language** (`"auto"` \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>)?  | A string representing the desired language used for the map's labels and UI components. Languages can only be set on Mapbox vector tile sources. Valid language strings must be a [BCP-47 language code](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_subtags) . Unsupported BCP-47 codes will not include any translations. Invalid codes will result in an recoverable error. If a label has no translation for the selected language, it will display in the label's local language. If param is set to `auto` , GL JS will select a user's preferred language as determined by the browser's [`window.navigator.language`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) property. If the `locale` property is not set separately, this language will also be used to localize the UI for supported languages. If param is set to `undefined` or `null` , it will remove the current map language and reset the language used for translating map labels and UI components. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setLanguage('es');
```

```js
map.setLanguage(['en-GB', 'en-US']);
```

```js
map.setLanguage('auto');
```

```js
map.setLanguage();
```

### getWorldview()

Returns the code for the map's worldview.

#### Returns

[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String): Returns the map's worldview code.

#### Example

```js
const worldview = map.getWorldview();
```

### setWorldview()

Sets the map's worldview.

#### Parameters

| Name | Description |
| --- | --- |
| **worldview** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | A string representing the desired worldview. A worldview determines the way that certain disputed boundaries are rendered. Valid worldview strings must be an [ISO alpha-2 country code](https://en.wikipedia.org/wiki/ISO_3166-1#Current_codes) . Unsupported ISO alpha-2 codes will fall back to the TileJSON's default worldview. Invalid codes will result in a recoverable error. If param is set to `undefined` or `null` , it will cause the map to fall back to the TileJSON's default worldview. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setWorldview('JP');
```

```js
map.setWorldview();
```

### Point conversion

### getProjection()

Returns a [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) object that defines the current map projection.

#### Returns

ProjectionSpecification: The [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) defining the current map projection.

#### Example

```js
const projection = map.getProjection();
```

### setProjection()

Sets the map's projection. If called with `null` or `undefined`, the map will reset to Mercator.

#### Parameters

| Name | Description |
| --- | --- |
| **projection** (ProjectionSpecification \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The projection that the map should be rendered in. This can be a [projection](https://docs.mapbox.com/mapbox-gl-js/style-spec/projection/) object or a string of the projection's name. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setProjection('albers');
map.setProjection({
    name: 'albers',
    center: [35, 55],
    parallels: [20, 60]
});
```

#### Related

-   [Example: Display a web map using an alternate projection](https://docs.mapbox.com/mapbox-gl-js/example/map-projection/)
-   [Example: Use different map projections for web maps](https://docs.mapbox.com/mapbox-gl-js/example/projections/)

### project()

Returns a [Point](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#point) representing pixel coordinates, relative to the map's `container`, that correspond to the specified geographical location.

When the map is pitched and `lnglat` is completely behind the camera, there are no pixel coordinates corresponding to that location. In that case, the `x` and `y` components of the returned [Point](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#point) are set to Number.MAX_VALUE.

#### Parameters

| Name | Description |
| --- | --- |
| **lnglat** [LngLatLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatlike)  | The geographical location to project. |
| **altitude** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | (optional) altitude above the map plane in meters. |

#### Returns

[Point](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#point): The [Point](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#point) corresponding to `lnglat` , relative to the map's `container` .

#### Example

```js
const coordinate = [-122.420679, 37.772537];
const point = map.project(coordinate);
```

### unproject()

Returns a [LngLat](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglat) representing geographical coordinates that correspond to the specified pixel coordinates. If horizon is visible, and specified pixel is above horizon, returns a [LngLat](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglat) corresponding to point on horizon, nearest to the point.

#### Parameters

| Name | Description |
| --- | --- |
| **point** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike)  | The pixel coordinates to unproject. |
| **altitude** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | (optional) altitude above the map plane in meters. |

#### Returns

[LngLat](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglat): The [LngLat](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglat) corresponding to `point` .

#### Example

```js
map.on('click', (e) => {
    // When the map is clicked, get the geographic coordinate.
    const coordinate = map.unproject(e.point);
});
```

### Movement state

### isMoving()

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

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): True if the map is moving.

#### Example

```js
const isMoving = map.isMoving();
```

### isZooming()

Returns true if the map is zooming due to a camera animation or user gesture.

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): True if the map is zooming.

#### Example

```js
const isZooming = map.isZooming();
```

### isRotating()

Returns true if the map is rotating due to a camera animation or user gesture.

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): True if the map is rotating.

#### Example

```js
map.isRotating();
```

### Working with events

### on()

Adds a listener for events of a specified type, optionally limited to features in a specified style layer.

#### Parameters

| Name | Description |
| --- | --- |
| **type** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | 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.
| Event | Compatible with `layerId` |
| --- | --- |
| [`mousedown`](#map.event:mousedown) | yes |
| [`mouseup`](#map.event:mouseup) | yes |
| [`mouseover`](#map.event:mouseover) | yes |
| [`mouseout`](#map.event:mouseout) | yes |
| [`mousemove`](#map.event:mousemove) | yes |
| [`mouseenter`](#map.event:mouseenter) | yes (required) |
| [`mouseleave`](#map.event:mouseleave) | yes (required) |
| [`preclick`](#map.event:preclick) |  |
| [`click`](#map.event:click) | yes |
| [`dblclick`](#map.event:dblclick) | yes |
| [`contextmenu`](#map.event:contextmenu) | yes |
| [`touchstart`](#map.event:touchstart) | yes |
| [`touchend`](#map.event:touchend) | yes |
| [`touchcancel`](#map.event:touchcancel) | yes |
| [`wheel`](#map.event:wheel) |  |
| [`resize`](#map.event:resize) |  |
| [`remove`](#map.event:remove) |  |
| [`touchmove`](#map.event:touchmove) |  |
| [`movestart`](#map.event:movestart) |  |
| [`move`](#map.event:move) |  |
| [`moveend`](#map.event:moveend) |  |
| [`dragstart`](#map.event:dragstart) |  |
| [`drag`](#map.event:drag) |  |
| [`dragend`](#map.event:dragend) |  |
| [`zoomstart`](#map.event:zoomstart) |  |
| [`zoom`](#map.event:zoom) |  |
| [`zoomend`](#map.event:zoomend) |  |
| [`rotatestart`](#map.event:rotatestart) |  |
| [`rotate`](#map.event:rotate) |  |
| [`rotateend`](#map.event:rotateend) |  |
| [`pitchstart`](#map.event:pitchstart) |  |
| [`pitch`](#map.event:pitch) |  |
| [`pitchend`](#map.event:pitchend) |  |
| [`boxzoomstart`](#map.event:boxzoomstart) |  |
| [`boxzoomend`](#map.event:boxzoomend) |  |
| [`boxzoomcancel`](#map.event:boxzoomcancel) |  |
| [`webglcontextlost`](#map.event:webglcontextlost) |  |
| [`webglcontextrestored`](#map.event:webglcontextrestored) |  |
| [`load`](#map.event:load) |  |
| [`render`](#map.event:render) |  |
| [`idle`](#map.event:idle) |  |
| [`error`](#map.event:error) |  |
| [`data`](#map.event:data) |  |
| [`styledata`](#map.event:styledata) |  |
| [`sourcedata`](#map.event:sourcedata) |  |
| [`dataloading`](#map.event:dataloading) |  |
| [`styledataloading`](#map.event:styledataloading) |  |
| [`sourcedataloading`](#map.event:sourcedataloading) |  |
| [`styleimagemissing`](#map.event:styleimagemissing) |  |
| [`style.load`](#map.event:style.load) |  |

 |
| **listener** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)  | The function to be called when the event is fired. |
| **layerIds** ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>)  | (optional) The ID(s) of a style layer(s). If you provide a `layerId` , the listener will be triggered only if its location is within a visible feature in these layers, and the event will have a `features` property containing an array of the matching features. If you do not provide `layerIds` , the listener will be triggered by a corresponding event happening anywhere on the map, and the event will not have a `features` property. Note that many event types are not compatible with the optional `layerIds` parameter. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Set an event listener that will fire
// when the map has finished loading.
map.on('load', () => {
    // Add a new layer.
    map.addLayer({
        id: 'points-of-interest',
        source: {
            type: 'vector',
            url: 'mapbox://mapbox.mapbox-streets-v8'
        },
        'source-layer': 'poi_label',
        type: 'circle',
        paint: {
            // Mapbox Style Specification paint properties
        },
        layout: {
            // Mapbox Style Specification layout properties
        }
    });
});
```

```js
// 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 mapboxgl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(`Country name: ${e.features[0].properties.name}`)
        .addTo(map);
});
```

```js
// Set an event listener that will fire
// when a feature on the countries or background layers of the map is clicked.
map.on('click', ['countries', 'background'], (e) => {
    new mapboxgl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(`Country name: ${e.features[0].properties.name}`)
        .addTo(map);
});
```

#### Related

-   [Example: Add 3D terrain to a map](https://docs.mapbox.com/mapbox-gl-js/example/add-terrain/)
-   [Example: Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/)
-   [Example: Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
-   [Example: Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)
-   [Example: Display popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)

### once()

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

#### Parameters

| Name | Description |
| --- | --- |
| **type** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The event type to listen for; one of `'mousedown'` , `'mouseup'` , `'preclick'` , `'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. |
| **layerIds** ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>)  | (optional) The ID(s) of a style layer(s). If you provide `layerIds` , the listener will be triggered only if its location is within a visible feature in these layers, and the event will have a `features` property containing an array of the matching features. If you do not provide `layerIds` , the listener will be triggered by a corresponding event happening anywhere on the map, and the event will not have a `features` property. Note that many event types are not compatible with the optional `layerIds` parameter. |
| **listener** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)  | The function to be called when the event is fired. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Log the coordinates of a user's first map touch.
map.once('touchstart', (e) => {
    console.log(`The first map touch was at: ${e.lnglat}`);
});
```

```js
// Log the coordinates of a user's first map touch
// on a specific layer.
map.once('touchstart', 'my-point-layer', (e) => {
    console.log(`The first map touch on the point layer was at: ${e.lnglat}`);
});
```

```js
// Log the coordinates of a user's first map touch
// on specific layers.
map.once('touchstart', ['my-point-layer', 'my-point-layer-2'], (e) => {
    console.log(`The first map touch on the point layer was at: ${e.lnglat}`);
});
```

#### Related

-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
-   [Example: Animate the camera around a point with 3D terrain](https://docs.mapbox.com/mapbox-gl-js/example/free-camera-point/)
-   [Example: Play map locations as a slideshow](https://docs.mapbox.com/mapbox-gl-js/example/playback-locations/)

### off()

Removes an event listener previously added with [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), optionally limited to layer-specific events.

#### Parameters

| Name | Description |
| --- | --- |
| **type** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The event type previously used to install the listener. |
| **listener** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)  | The function previously installed as a listener. |
| **layerIds** ([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>)  | (optional) The layer ID(s) previously used to install the listener. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Create a function to print coordinates while a mouse is moving.
function onMove(e) {
    console.log(`The mouse is moving: ${e.lngLat}`);
}
// Create a function to unbind the `mousemove` event.
function onUp(e) {
    console.log(`The final coordinates are: ${e.lngLat}`);
    map.off('mousemove', onMove);
}
// When a click occurs, bind both functions to mouse events.
map.on('mousedown', (e) => {
    map.on('mousemove', onMove);
    map.once('mouseup', onUp);
});
```

#### Related

-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### Querying features

### queryRenderedFeatures()

Returns an array of [GeoJSON](http://geojson.org/) [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) representing visible features that satisfy the query parameters.

#### Parameters

| Name | Description |
| --- | --- |
| **geometry** ([PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike)>)?  | The geometry of the query region in pixels: either a single point or bottom left and top right points describing a bounding box, where the origin is at the top left. Omitting this parameter (by calling [Map#queryRenderedFeatures](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#queryrenderedfeatures) with zero arguments, or with only an `options` argument) is equivalent to passing a bounding box encompassing the entire map viewport. Only values within the existing viewport are supported. |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?  | Options object. |
| **options.filter** [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)?  | A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) to limit query results. |
| **options.layers** [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>?  | An array of [style layer IDs](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) for the query to inspect. Only features within these layers will be returned. If `target` and `layers` are both undefined, the query will inspect all layers and featuresets in the root style, as well as all featuresets in the root style imports. |
| **options.target** [TargetDescriptor](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#targetdescriptor)?  | A query target to inspect. This could be a [style layer ID](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) or a [FeaturesetDescriptor](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#featuresetdescriptor) . Only features within layers referenced by the query target will be returned. If `target` and `layers` are both undefined, the query will inspect all layers and featuresets in the root style, as well as all featuresets in the root style imports. |
| **options.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if the [options.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>: An array of [GeoJSON](http://geojson.org/) [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) .

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. `null`, `Array`, and `Object` values are not supported.

For featuresets in the style imports, each feature includes top-level `target` and an optional `namespace` property as defined in [TargetFeature](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#targetfeature). The `target` property represents the query target associated with the feature, while the optional `namespace` property is included to prevent feature ID collisions when layers in the query target reference multiple sources.

For layers and featuresets in the root style, 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 antimeridian 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.

For model layers, id or a property "id" is required to be specified per feature in the source.

#### Example

```js
// Find all features at a point
const features = map.queryRenderedFeatures(
  [20, 35],
  {target: {layerId: 'my-layer-name'}}
);
```

```js
// Find all features within a static bounding box
const features = map.queryRenderedFeatures(
  [[10, 20], [30, 50]],
  {target: {layerId: 'my-layer-name'}}
);
```

```js
// Find all features within a bounding box around a point
const width = 10;
const height = 20;
const features = map.queryRenderedFeatures([
    [point.x - width / 2, point.y - height / 2],
    [point.x + width / 2, point.y + height / 2]
], {target: {layerId: 'my-layer-name'}});
```

```js
// Query all rendered features from a single layer
const features = map.queryRenderedFeatures({target: {layerId: 'my-layer-name'}});

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

// Query all rendered features from a `poi` featureset in the `basemap` style import
const features = map.queryRenderedFeatures({target: {featuresetId: 'poi', importId: 'basemap'}});
```

#### Related

-   [Example: Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/)
-   [Example: Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
-   [Example: Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)

### querySourceFeatures()

Returns an array of [GeoJSON](http://geojson.org/) [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.

#### Parameters

| Name | Description |
| --- | --- |
| **sourceId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the vector tile or GeoJSON source to query. |
| **parameters** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?  | Options object. |
| **parameters.filter** [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)?  | A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) to limit query results. |
| **parameters.sourceLayer** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored. |
| **parameters.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if the [parameters.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>: An array of [GeoJSON](http://geojson.org/) [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2) .

In contrast to [Map#queryRenderedFeatures](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#queryrenderedfeatures), this function returns all features matching the query parameters, whether or not they are rendered by the current style (in other words, are visible). The domain of the query includes all currently-loaded vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently visible viewport.

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

#### Example

```js
// Find all features in one source layer in a vector source
const features = map.querySourceFeatures('your-source-id', {
    sourceLayer: 'your-source-layer'
});
```

#### Related

-   [Example: Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)

### queryRasterValue()

EXPERIMENTAL

Returns the value of a raster source at a given coordinate. Currently, this API only supports raster array sources.

#### Parameters

| Name | Description |
| --- | --- |
| **sourceId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the raster source to query. |
| **lnglat** [LngLatLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatlike)  | The mercator coordinates at which to query the raster. |
| **parameters** RasterQueryParameters?  | (optional) Parameters of the query. |
| **parameters.bands** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | (optional) The IDs of the band to query raster array source. |
| **parameters.layerName** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | (optional) The name of the layer to query raster array source. If not provided, all layers in the source will be queried. |

#### Returns

[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<(RasterQueryResult \| null)>: Promise which resolves to the result of the raster array query, containing the value at the specified point. If not specified all bands of the raster array source layers will be queried.

#### Example

```js
const value = await map.queryRasterValue('my-raster-source', {lng: -122.4194, lat: 37.7749}, {bands: ['1000']});
console.log(value['Layer']) // {1000: [0.34]}
```

### isPointOnSurface()

Determines if the given point is located on a visible map surface.

#### Parameters

| Name | Description |
| --- | --- |
| **point** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike)  | The point to be checked, specified as an array of two numbers representing the x and y coordinates, or as a [Point](https://docs.mapbox.com/mapbox-gl-js/api/geography/#point) object. |

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): Returns `true` if the point is on the visible map surface, otherwise returns `false` .

#### Example

```js
const pointOnSurface = map.isPointOnSurface([100, 200]);
```

### addInteraction()

Add an interaction — a named gesture handler of a given type.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the interaction. |
| **interaction** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | The interaction object with the following properties. |
| **interaction.filter** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?  | Filter expression to narrow down the interaction to a subset of features under the pointer. |
| **interaction.handler** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)  | A handler function that will be invoked on the gesture and receive a `{feature, interaction}` object as a parameter. |
| **interaction.target** [TargetDescriptor](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#targetdescriptor)?  | The interaction target, which can be either a reference to a layer or a reference to a featureset in a style import. Use `{layerId: string}` to reference features in the root style layer, or `{featuresetId: string, importId?: string}` to reference features in an imported style. |
| **interaction.type** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The type of gesture to handle (e.g. 'click'). |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.addInteraction('poi-click', {
  type: 'click',
  target: {featuresetId: 'poi', importId: 'basemap'},
  handler(e) {
    console.log(e.feature);
  }
});
```

```js
map.addInteraction('building-mouseenter', {
  type: 'mouseenter',
  target: {featuresetId: 'buildings', importId: 'basemap'},
  handler: (e) => {
    map.setFeatureState(e.feature, {highlight: true});
  }
});
```

```js
map.addInteraction('building-mouseleave', {
  type: 'mouseleave',
  target: {featuresetId: 'buildings', importId: 'basemap'},
  handler: (e) => {
    map.setFeatureState(e.feature, {highlight: true});
    // Propagate the event so that the handler is called for each feature.
    return false;
  }
});
```

### removeInteraction()

Remove an interaction previously added with `addInteraction`.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The id of the interaction to remove. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.removeInteraction('poi-click');
```

### getCooperativeGestures()

Gets the state of `cooperativeGestures`.

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): Returns the `cooperativeGestures` boolean.

#### Example

```js
const cooperativeGesturesEnabled = map.getCooperativeGestures();
```

### setCooperativeGestures()

Sets the state of `cooperativeGestures`.

#### Parameters

| Name | Description |
| --- | --- |
| **enabled** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)  | If `true` , scroll zoom will require pressing the ctrl or ⌘ key while scrolling to zoom map, and touch pan will require using two fingers while panning to move the map. Touch pitch will require three fingers to activate if enabled. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setCooperativeGestures(true);
```

### Working with styles

### setStyle()

Updates the map's Mapbox style object with a new value.

If a style is already set when this is used and the `diff` option is set to `true`, the map renderer will attempt to compare the given style against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current style and the given style are different in any way, the map renderer will force a full update, removing the current style and building the given one from scratch.

#### Parameters

| Name | Description |
| --- | --- |
| **style** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| null)  | A JSON object conforming to the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/) , or a URL to such JSON. |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?  | Options object. |
| **options.config** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) (default `null`) | The initial configuration options for the style fragments. Each key in the object is a fragment ID (e.g., `basemap` ) and each value is a configuration object. |
| **options.diff** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | If false, force a 'full' update, removing the current style and building the given one instead of attempting a diff-based update. |
| **options.localIdeographFontFamily** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) (default `'sans-serif'`) | Defines a CSS font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges. In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). Set to `false` , to enable font settings from the map's style for these glyph ranges. Forces a full update. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setStyle("mapbox://styles/mapbox/streets-v11");
```

```js
map.setStyle("mapbox://styles/mapbox/standard", {
    "config": {
        "basemap": {
            "lightPreset": "night"
        }
    }
});
```

#### Related

-   [Example: Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/)

### getStyle()

Returns the map's Mapbox [style](https://docs.mapbox.com/help/glossary/style/) object, a JSON object which can be used to recreate the map's style.

For the Mapbox Standard style or any "fragment" style (which is a style with `fragment: true` or a `schema` property defined), this method returns an empty style with no layers or sources. The original style is wrapped into an import with the ID `basemap` as a fragment style and is not intended to be used directly. This design ensures that user logic is not tied to style internals, allowing Mapbox to roll out style updates seamlessly and consistently.

#### Returns

(StyleSpecification \| void): The map's style JSON object.

#### Example

```js
map.on('load', () => {
    const styleJson = map.getStyle();
});
```

### isStyleLoaded()

Returns a Boolean indicating whether the map's style is fully loaded.

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether the style is fully loaded.

#### Example

```js
const styleLoadStatus = map.isStyleLoaded();
```

### Sources

### addSource()

Adds a source to the map's style.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the source to add. Must not conflict with existing sources. |
| **source** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | The source object, conforming to the Mapbox Style Specification's [source definition](https://docs.mapbox.com/style-spec/reference/sources/) or [CanvasSourceOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/sources/#canvassourceoptions) . |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.addSource('my-data', {
    type: 'vector',
    url: 'mapbox://myusername.tilesetid'
});
```

```js
map.addSource('my-data', {
    "type": "geojson",
    "data": {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": [-77.0323, 38.9131]
        },
        "properties": {
            "title": "Mapbox DC",
            "marker-symbol": "monument"
        }
    }
});
```

#### Related

-   Example: Vector source: [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)
-   Example: GeoJSON source: [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)
-   Example: Raster DEM source: [Add hillshading](https://docs.mapbox.com/mapbox-gl-js/example/hillshade/)

### isSourceLoaded()

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

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the source to be checked. |

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether the source is loaded.

#### Example

```js
const sourceLoaded = map.isSourceLoaded('bathymetry-data');
```

### areTilesLoaded()

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

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether all tiles are loaded.

#### Example

```js
const tilesLoaded = map.areTilesLoaded();
```

### removeSource()

Removes a source from the map's style.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the source to remove. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.removeSource('bathymetry-data');
```

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

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the source to get. |

#### Returns

[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?: 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 Mapbox Style Specification's [Sources](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) page.

#### Example

```js
const sourceObject = map.getSource('points');
```

#### Related

-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)
-   [Example: Animate a point](https://docs.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)
-   [Example: Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)

### Images

### addImage()

Add an image to the style. This image can be displayed on the map like any other icon in the style's [sprite](https://docs.mapbox.com/mapbox-gl-js/style-spec/sprite/) using the image's ID with [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image), [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern), [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern), or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern). A [Map.event:error](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:error) event will be fired if there is not enough space in the sprite to add this image.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the image. |
| **image** ([HTMLImageElement](https://developer.mozilla.org/docs/Web/API/HTMLImageElement) \| ImageBitmap \| ImageData \| {width: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), height: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), data: ([Uint8Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) \| [Uint8ClampedArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray))} \| [StyleImageInterface](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#styleimageinterface))  | The image as an `HTMLImageElement` , `ImageData` , `ImageBitmap` or object with `width` , `height` , and `data` properties with the same format as `ImageData` . |
| **options** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null) (default `{}`) | Options object. |
| **options.content** [[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)]  | `[x1, y1, x2, y2]` If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field` . |
| **options.pixelRatio** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `1`) | The ratio of pixels in the image to physical pixels on the screen. |
| **options.sdf** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `false`) | Whether the image should be interpreted as an SDF image. |
| **options.stretchX** [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)]>  | `[[x1, x2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally. |
| **options.stretchY** [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)]>  | `[[y1, y2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically. |

#### Example

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

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

#### Related

-   Example: Use `HTMLImageElement` : [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)
-   Example: Use `ImageData` : [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/)

### updateImage()

Update an existing image in a style. This image can be displayed on the map like any other icon in the style's [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image), [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern), [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern), or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the image. |
| **image** ([HTMLImageElement](https://developer.mozilla.org/docs/Web/API/HTMLImageElement) \| ImageBitmap \| ImageData \| [StyleImageInterface](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#styleimageinterface))  | The image as an `HTMLImageElement` , [`ImageData`](https://developer.mozilla.org/en-US/docs/Web/API/ImageData) , [`ImageBitmap`](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap) or object with `width` , `height` , and `data` properties with the same format as `ImageData` . |

#### Example

```js
// Load an image from an external URL.
map.loadImage('http://placekitten.com/50/50', (error, image) => {
    if (error) throw error;
    // 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', image);
});
```

### 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](https://docs.mapbox.com/help/glossary/sprite/) and any images that have been added at runtime using [Map#addImage](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addimage).

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the image. |

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether the image exists.

#### Example

```js
// Check if an image with the ID 'cat' exists in
// the style's sprite.
const catIconExists = map.hasImage('cat');
```

### removeImage()

Remove an image from a style. This can be an image from the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) or any images that have been added at runtime using [Map#addImage](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addimage).

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the image. |

#### Example

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

### loadImage()

Load an image from an external URL to be used with [Map#addImage](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addimage). External domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).

#### Parameters

| Name | Description |
| --- | --- |
| **url** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The URL of the image file. Image file must be in png, webp, or jpg format. |
| **callback** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)  | Expecting `callback(error, data)` . Called when the image has loaded or with an error argument if there is an error. |

#### Example

```js
// Load an image from an external URL.
map.loadImage('http://placekitten.com/50/50', (error, image) => {
    if (error) throw error;
    // Add the loaded image to the style's sprite with the ID 'kitten'.
    map.addImage('kitten', image);
});
```

#### Related

-   [Example: Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)

### 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](https://docs.mapbox.com/help/glossary/sprite/) and any images that have been added at runtime using [Map#addImage](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addimage).

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>: An Array of strings containing the names of all sprites/images currently available in the map.

#### Example

```js
const allImages = map.listImages();
```

### Models

### addModel()

Add a model to the style. This model can be displayed on the map like any other model in the style using the model ID in conjunction with a 2D vector layer. This API can also be used for updating a model. If the model for a given `modelId` was already added, it gets replaced by the new model.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the model. |
| **url** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Pointing to the model to load. |

#### Example

```js
// If the style does not already contain a model with ID 'tree',
// load a tree model and then use a geojson to show it.
map.addModel('tree', 'http://path/to/my/tree.glb');
map.addLayer({
    "id": "tree-layer",
    "type": "model",
    "source": "trees",
    "source-layer": "trees",
    "layout": {
        "model-id": "tree"
    }
});
```

### hasModel()

Check whether or not a model with a specific ID exists in the style. This checks both models in the style and any models that have been added at runtime using [Map#addModel](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addmodel).

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the model. |

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether the model exists.

#### Example

```js
// Check if a model with the ID 'tree' exists in
// the style.
const treeModelExists = map.hasModel('tree');
```

### removeModel()

Remove an model from a style. This can be a model from the style original or any models that have been added at runtime using [Map#addModel](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addmodel).

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the model. |

#### Example

```js
// If an model with the ID 'tree' exists in
// the style, remove it.
if (map.hasModel('tree')) map.removeModel('tree');
```

### listModels()

Returns an Array of strings containing the IDs of all models currently available in the map. This includes both models from the style and any models that have been added at runtime using [Map#addModel](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addmodel).

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>: An Array of strings containing the names of all model IDs currently available in the map.

#### Example

```js
const allModels = map.listModels();
```

### Layers

### addLayer()

Adds a [Mapbox style layer](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) 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 [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers).

#### Parameters

<table class="table table--fixed table--compact" style="width:100%;table-layout:fixed"><colgroup><col width="28%"><col></colgroup><thead><tr class="bg-gray-faint"><th style="border-top-left-radius:4px">Name</th><th style="border-top-right-radius:4px">Description</th></tr></thead><tbody><tr><td><strong>layer</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a> | <a href="/mapbox-gl-js/api/properties/#customlayerinterface">CustomLayerInterface</a>)</span>&nbsp;</td><td><span>The layer to add, conforming to either the Mapbox Style Specification's <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers">layer definition</a> or, less commonly, the <a href="/mapbox-gl-js/api/properties/#customlayerinterface">CustomLayerInterface</a> specification. The Mapbox Style Specification's layer definition is appropriate for most layers.</span></td></tr><tr><td><strong>layer.filter</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a>?</span>&nbsp;</td><td><span>(optional) An expression specifying conditions on source features. Only features that match the filter are displayed. The Mapbox Style Specification includes more information on the limitations of the <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter"><code>filter</code></a> parameter and a complete list of available <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/">expressions</a> . If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed.</span></td></tr><tr><td><strong>layer.id</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;</td><td><span>A unique identifier that you define.</span></td></tr><tr><td><strong>layer.layout</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>?</span>&nbsp;</td><td><span>(optional) Layout properties for the layer. Available layout properties vary by <code>layer.type</code> . A full list of layout properties for each layer type is available in the <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/">Mapbox Style Specification</a> . If no layout properties are specified, default values will be used.</span></td></tr><tr><td><strong>layer.maxzoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a>?</span>&nbsp;</td><td><span>(optional) The maximum zoom level for the layer. At zoom levels equal to or greater than the maxzoom, the layer will be hidden. The value can be any number between <code>0</code> and <code>24</code> (inclusive). If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.</span></td></tr><tr><td><strong>layer.metadata</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>?</span>&nbsp;</td><td><span>(optional) Arbitrary properties useful to track with the layer, but do not influence rendering.</span></td></tr><tr><td><strong>layer.minzoom</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number">number</a>?</span>&nbsp;</td><td><span>(optional) The minimum zoom level for the layer. At zoom levels less than the minzoom, the layer will be hidden. The value can be any number between <code>0</code> and <code>24</code> (inclusive). If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.</span></td></tr><tr><td><strong>layer.paint</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>?</span>&nbsp;</td><td><span>(optional) Paint properties for the layer. Available paint properties vary by <code>layer.type</code> . A full list of paint properties for each layer type is available in the <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/">Mapbox Style Specification</a> . If no paint properties are specified, default values will be used.</span></td></tr><tr><td><strong>layer.renderingMode</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>?</span>&nbsp;</td><td><span>This is only applicable for layers with the type <code>custom</code> . See <a href="/mapbox-gl-js/api/properties/#customlayerinterface">CustomLayerInterface</a> for more information.</span></td></tr><tr><td><strong>layer.slot</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>?</span>&nbsp;</td><td><span>(optional) The identifier of a <a href="https://docs.mapbox.com/style-spec/reference/slots/"><code>slot</code></a> layer that will be used to position this style layer. A <code>slot</code> layer serves as a predefined position in the layer order for inserting associated layers. <em>Note</em> : During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance. This process might lead to a rearrangement of layers. Layers draped over globe and terrain, such as <code>fill</code> , <code>line</code> , <code>background</code> , <code>hillshade</code> , and <code>raster</code> , are rendered first. These layers are rendered underneath symbols, regardless of whether they are placed in the middle or top slots or without a designated slot.</span></td></tr><tr><td><strong>layer.source</strong>&nbsp;<span>(<a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a> | <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a>)?</span>&nbsp;</td><td><span>The data source for the layer. Reference a source that has <em>already been defined</em> using the source's unique id. Reference a <em>new source</em> using a source object (as defined in the <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/">Mapbox Style Specification</a> ) directly. This is <strong>required</strong> for all <code>layer.type</code> options <em>except</em> for <code>custom</code> and <code>background</code> .</span></td></tr><tr><td><strong>layer.sourceLayer</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>?</span>&nbsp;</td><td><span>(optional) The name of the <a href="https://docs.mapbox.com/help/glossary/source-layer/">source layer</a> within the specified <code>layer.source</code> to use for this style layer. This is only applicable for vector tile sources and is <strong>required</strong> when <code>layer.source</code> is of the type <code>vector</code> .</span></td></tr><tr><td><strong>layer.type</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a></span>&nbsp;</td><td><span>The type of layer (for example <code>fill</code> or <code>symbol</code> ). A list of layer types is available in the <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type">Mapbox Style Specification</a> .<p>This can also be <code>custom</code>. For more information, see <a href="/mapbox-gl-js/api/properties/#customlayerinterface">CustomLayerInterface</a>.</p></span></td></tr><tr><td><strong>beforeId</strong>&nbsp;<span><a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String">string</a>?</span>&nbsp;</td><td><span>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. <em>Note</em> : Layers can only be rearranged within the same <code>slot</code> . The new layer must share the same <code>slot</code> as the existing layer to be positioned underneath it. If the layers are in different slots, the <code>beforeId</code> parameter will be ignored and the new layer will be appended to the end of the layers array. During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance. This process might lead to a rearrangement of layers. Layers draped over globe and terrain, such as <code>fill</code> , <code>line</code> , <code>background</code> , <code>hillshade</code> , and <code>raster</code> , are rendered first. These layers are rendered underneath symbols, regardless of whether they are placed in the middle or top slots or without a designated slot.</span></td></tr></tbody></table>

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Add a circle layer with a vector source
map.addLayer({
    id: 'points-of-interest',
    source: {
        type: 'vector',
        url: 'mapbox://mapbox.mapbox-streets-v8'
    },
    'source-layer': 'poi_label',
    type: 'circle',
    paint: {
    // Mapbox Style Specification paint properties
    },
    layout: {
    // Mapbox Style Specification layout properties
    }
});
```

```js
// Define a source before using it to create a new layer
map.addSource('state-data', {
    type: 'geojson',
    data: 'path/to/data.geojson'
});

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

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

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

#### Related

-   [Example: Select features around a clicked point](https://docs.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures-around-point/) (fill layer)
-   [Example: Add a new layer below labels](https://docs.mapbox.com/mapbox-gl-js/example/geojson-layer-in-stack/)
-   [Example: Create and style clusters](https://docs.mapbox.com/mapbox-gl-js/example/cluster/) (circle layer)
-   [Example: Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/) (line layer)
-   [Example: Add a WMS layer](https://docs.mapbox.com/mapbox-gl-js/example/wms/) (raster layer)

### getSlot()

Returns current slot of the layer.

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of the layer to retrieve its current slot. |

#### Returns

([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| null): The slot identifier or `null` if layer doesn't have it.

#### Example

```js
map.getSlot('roads');
```

### setSlot()

Sets or removes [a slot](https://docs.mapbox.com/style-spec/reference/slots/) of style layer.

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of style layer. |
| **slot** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of slot. If `null` or `undefined` is provided, the method removes slot. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Sets new slot for style layer
map.setSlot("heatmap", "top");
```

### addImport()

Adds new [import](https://docs.mapbox.com/style-spec/reference/imports/) to current style.

#### Parameters

| Name | Description |
| --- | --- |
| **importSpecification** ImportSpecification  | Specification of import. |
| **beforeId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | (optional) Identifier of an existing import to insert the new import before. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Add streets style to empty map
new Map({style: {version: 8, sources: {}, layers: []}})
    .addImport({id: 'basemap', url: 'mapbox://styles/mapbox/streets-v12'});
```

```js
// Add new style before already added
const map = new Map({
    imports: [
        {
            id: 'basemap',
            url: 'mapbox://styles/mapbox/standard'
        }
    ],
    style: {
        version: 8,
        sources: {},
        layers: []
    }
});

map.addImport({
    id: 'lakes',
    url: 'https://styles/mapbox/streets-v12'
}, 'basemap');
```

### updateImport()

Updates already added to style import.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of import to update. |
| **importSpecification** (ImportSpecification \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))  | Import specification or URL of style. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Update import with new data
map.updateImport('basemap', {
    data: {
        version: 8,
        sources: {},
        layers: [
            {
                id: 'background',
                type: 'background',
                paint: {
                    'background-color': '#eee'
                }
            }
        ]
    }
});
```

```js
// Change URL of imported style
map.updateImport('basemap', 'mapbox://styles/mapbox/other-standard');
```

### removeImport()

Removes added to style import.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of import to remove. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Removes imported style
map.removeImport('basemap');
```

### moveImport()

Moves import to position before another import, specified with `beforeId`. Order of imported styles corresponds to order of their layers.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of import to move. |
| **beforeId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The identifier of an existing import to move the new import before. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
const map = new Map({
    style: {
        imports: [
            {
                id: 'basemap',
                url: 'mapbox://styles/mapbox/standard'
            },
            {
                id: 'streets-v12',
                url: 'mapbox://styles/mapbox/streets-v12'
            }
        ]
    }
});
// Place `streets-v12` import before `basemap`
map.moveImport('streets-v12', 'basemap');
```

### moveLayer()

Moves a layer to a different z-position.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to move. |
| **beforeId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/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. *Note* : Layers can only be rearranged within the same `slot` . The new layer must share the same `slot` as the existing layer to be positioned underneath it. If the layers are in different slots, the `beforeId` parameter will be ignored and the new layer will be appended to the end of the layers array. During 3D globe and terrain rendering, GL JS aims to batch multiple layers together for optimal performance. This process might lead to a rearrangement of layers. Layers draped over globe and terrain, such as `fill` , `line` , `background` , `hillshade` , and `raster` , are rendered first. These layers are rendered underneath symbols, regardless of whether they are placed in the middle or top slots or without a designated slot. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// 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');
```

### removeLayer()

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

If no such layer exists, an `error` event is fired.

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | ID of the layer to remove. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// If a layer with ID 'state-data' exists, remove it.
if (map.getLayer('state-data')) map.removeLayer('state-data');
```

#### Fires

[Map.event:error](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:error)

### getLayer()

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

#### Parameters

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to get. |

#### Returns

[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?: The layer with the specified ID, or `undefined` if the ID corresponds to no existing layers.

#### Example

```js
const stateDataLayer = map.getLayer('state-data');
```

#### Related

-   [Example: Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/)
-   [Example: Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/)

### getSlots()

Returns the IDs of all slots in the map's style.

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)>: The IDs of all slots in the map's style.

#### Example

```js
const slots = map.getSlots();
```

### setLayerZoomRange()

Sets the zoom extent for the specified style layer. The zoom extent includes the [minimum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-minzoom) and [maximum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-maxzoom)) at which the layer will be rendered.

Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the minimum zoom level of the *source layer* because the data does not exist at those zoom levels. If the minimum zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style layer will not be rendered at all zoom levels in the zoom range.

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to which the zoom extent will be applied. |
| **minzoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The minimum zoom to set (0-24). |
| **maxzoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The maximum zoom to set (0-24). |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

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

### setFilter()

Sets the filter for the specified style layer.

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

Use `setFilter` to show a subset of your source data.

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

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to which the filter will be applied. |
| **filter** ([Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array) \| null \| [undefined](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined))  | The filter, conforming to the Mapbox Style Specification's [filter definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) . If `null` or `undefined` is provided, the function removes any existing filter from the layer. |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)? (default `{}`) | Options object. |
| **options.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// display only features with the 'name' property 'USA'
map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);
```

```js
// display only features with five or more 'available-spots'
map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);
```

```js
// remove the filter for the 'bike-docks' style layer
map.setFilter('bike-docks', null);
```

#### Related

-   [Example: Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
-   [Example: Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)
-   [Example: Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)
-   [Tutorial: Show changes over time](https://docs.mapbox.com/help/tutorials/show-changes-over-time/)

### getFilter()

Returns the filter applied to the specified style layer.

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the style layer whose filter to get. |

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array): The layer's filter.

#### Example

```js
const filter = map.getFilter('myLayer');
```

### setPaintProperty()

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

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to set the paint property in. |
| **name** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/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 [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/) . |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)? (default `{}`) | Options object. |
| **options.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

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

#### Related

-   [Example: Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/)
-   [Example: Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/)
-   [Example: Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### getPaintProperty()

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

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to get the paint property from. |
| **name** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of a paint property to get. |

#### Returns

any: The value of the specified paint property.

#### Example

```js
const paintProperty = map.getPaintProperty('mySymbolLayer', 'icon-color');
```

### setLayoutProperty()

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

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to set the layout property in. |
| **name** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the layout property to set. |
| **value** any  | The value of the layout property. Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/) . |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)? (default `{}`) | Options object. |
| **options.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

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

#### Related

-   [Example: Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)

### getLayoutProperty()

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

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to get the layout property from. |
| **name** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the layout property to get. |

#### Returns

any: The value of the specified layout property.

#### Example

```js
const layoutProperty = map.getLayoutProperty('mySymbolLayer', 'icon-anchor');
```

### getLayerProperty()

Returns the value of a layout, paint, or root-level property in the specified style layer.

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to get the property from. |
| **name** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the property to get. Can be a paint or layout property, or a root-level layer property ( `minzoom` , `maxzoom` , `filter` , `slot` , `source` , `source-layer` ). |

#### Returns

any: The value of the specified property.

#### Example

```js
const minzoom = map.getLayerProperty('my-layer', 'minzoom');
```

### setLayerProperty()

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

#### Parameters

| Name | Description |
| --- | --- |
| **layerId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The ID of the layer to set the layout or paint property in. |
| **name** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the layout or paint property to set. |
| **value** any  | The value of the layout or paint property. Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/) . |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)? (default `{}`) | Options object. |
| **options.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setLayerProperty('my-layer', 'visibility', 'none');
```

### Style properties

### getGlyphsUrl()

Returns the glyphs URL of the current style.

#### Returns

[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String): Returns a glyph URL template.

#### Example

```js
map.getGlyphsUrl();
```

### setGlyphsUrl()

Sets a URL template for loading signed-distance-field glyph sets in PBF format. The URL must include `{fontstack}` and `{range}` tokens.

#### Parameters

| Name | Description |
| --- | --- |
| **url** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | A URL template for loading SDF glyph sets in PBF format. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setGlyphsUrl('mapbox://fonts/mapbox/{fontstack}/{range}.pbf');
```

### getSchema()

Returns the imported style schema.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the imported style (e.g. `basemap` ). |

#### Returns

SchemaSpecification: Returns the imported style schema, if exists.

#### Example

```js
map.getSchema('basemap');
```

### setSchema()

Sets the imported style schema value.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the imported style (e.g. `basemap` ). |
| **schema** SchemaSpecification  | The imported style schema. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setSchema('basemap', {lightPreset: {type: 'string', default: 'night', values: ['day', 'night']}});
```

### getConfig()

Returns the imported style configuration.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the imported style (e.g. `basemap` ). |

#### Returns

any: Returns the imported style configuration.

#### Example

```js
map.getConfig('basemap');
```

### setConfig()

Sets the imported style configuration value.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the imported style (e.g. `basemap` ). |
| **config** ConfigSpecification  | The imported style configuration value. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setConfig('basemap', {lightPreset: 'night', showPointOfInterestLabels: false});
```

### getConfigProperty()

Returns the value of a configuration property in the imported style.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the imported style (e.g. `basemap` ). |
| **configName** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the configuration property from the style. |

#### Returns

any: Returns the value of the configuration property.

#### Example

```js
map.getConfigProperty('basemap', 'showLabels');
```

### setConfigProperty()

Sets the value of a configuration property in the currently set style.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the imported style to set the config for (e.g. `basemap` ). |
| **configName** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The name of the configuration property from the style. |
| **value** any  | The value of the configuration property. Must be of a type appropriate for the property, as defined by the style configuration schema. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setConfigProperty('basemap', 'showLabels', false);
```

### setLights()

Adds a set of Mapbox style light to the map's style.

*Note: This light is not to confuse with our legacy light API used through [Map#setLight](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#setlight) and [Map#getLight](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#getlight)*.

#### Parameters

| Name | Description |
| --- | --- |
| **lights** [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<LightsSpecification>  | An array of lights to add, conforming to the Mapbox Style Specification's light definition. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Add a directional light
map.setLights([{
    "id": "sun_light",
    "type": "directional",
    "properties": {
        "color": "rgba(255.0, 0.0, 0.0, 1.0)",
        "intensity": 0.4,
        "direction": [200.0, 40.0],
        "cast-shadows": true,
        "shadow-intensity": 0.2
    }
}]);
```

### getLights()

Returns the lights added to the map.

#### Returns

[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)<LightSpecification>: Lights added to the map.

#### Example

```js
const lights = map.getLights();
```

### setLight()

Sets the any combination of light values.

_Note: that this API is part of the legacy light API, prefer using [Map#setLights](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#setlights).

#### Parameters

| Name | Description |
| --- | --- |
| **light** LightSpecification  | Light properties to set. Must conform to the [Light Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light) . |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)? (default `{}`) | Options object. |
| **options.validate** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setLight({
    "anchor": "viewport",
    "color": "blue",
    "intensity": 0.5
});
```

### getLight()

Returns the value of the light object.

#### Returns

LightSpecification: Light properties of the style.

#### Example

```js
const light = map.getLight();
```

### setTerrain()

Sets the terrain property of the style.

#### Parameters

| Name | Description |
| --- | --- |
| **terrain** TerrainSpecification  | Terrain properties to set. Must conform to the [Terrain Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/terrain/) . If `null` or `undefined` is provided, function removes terrain. Exaggeration could be updated for the existing terrain without explicitly specifying the `source` . |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.addSource('mapbox-dem', {
    'type': 'raster-dem',
    'url': 'mapbox://mapbox.mapbox-terrain-dem-v1',
    'tileSize': 512,
    'maxzoom': 14
});
// add the DEM source as a terrain layer with exaggerated height
map.setTerrain({'source': 'mapbox-dem', 'exaggeration': 1.5});
// update the exaggeration for the existing terrain
map.setTerrain({'exaggeration': 2});
```

### getTerrain()

Returns the terrain specification or `null` if terrain isn't set on the map.

#### Returns

(TerrainSpecification \| null): Terrain specification properties of the style.

#### Example

```js
const terrain = map.getTerrain();
```

### setFog()

Sets the fog property of the style.

#### Parameters

| Name | Description |
| --- | --- |
| **fog** FogSpecification  | The fog properties to set. Must conform to the [Fog Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/fog/) . If `null` or `undefined` is provided, this function call removes the fog from the map. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setFog({
    "range": [0.8, 8],
    "color": "#dc9f9f",
    "horizon-blend": 0.5,
    "high-color": "#245bde",
    "space-color": "#000000",
    "star-intensity": 0.15
});
```

#### Related

-   [Example: Add fog to a map](https://docs.mapbox.com/mapbox-gl-js/example/add-fog/)

### getFog()

Returns the fog specification or `null` if fog is not set on the map.

#### Returns

FogSpecification: Fog specification properties of the style.

#### Example

```js
const fog = map.getFog();
```

### setSnow()

EXPERIMENTAL

Sets the snow property of the style. *This API is experimental, not production ready and subject to change in future versions*.

#### Parameters

| Name | Description |
| --- | --- |
| **snow** SnowSpecification  | The snow properties to set. If `null` or `undefined` is provided, this function call removes the snow from the map. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setSnow({
      density: 1,
      intensity: 0.3
  });
```

### getSnow()

EXPERIMENTAL

Returns the snow specification or `null` if snow is not set on the map. *This API is experimental, not production ready and subject to change in future versions*.

#### Returns

SnowSpecification: Snow specification properties of the style.

#### Example

```js
const snow = map.getSnow();
```

### setRain()

EXPERIMENTAL

Sets the rain property of the style. *This API is experimental, not production ready and subject to change in future versions*.

#### Parameters

| Name | Description |
| --- | --- |
| **rain** RainSpecification  | The rain properties to set. If `null` or `undefined` is provided, this function call removes the rain from the map. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setRain({
      density: 1,
      intensity: 0.3,
      "distortion-strength": 0.3
  });
```

### getRain()

EXPERIMENTAL

Returns the rain specification or `null` if rain is not set on the map. *This API is experimental, not production ready and subject to change in future versions*.

#### Returns

RainSpecification: Rain specification properties of the style.

#### Example

```js
const rain = map.getRain();
```

### setColorTheme()

Sets the color-theme property of the style.

#### Parameters

| Name | Description |
| --- | --- |
| **colorTheme** ColorThemeSpecification  | The color-theme properties to set. If `null` or `undefined` is provided, this function call removes the color-theme from the map. Note: Calling this function triggers a full reload of tiles. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setColorTheme({
    "data": "iVBORw0KGgoAA..."
});
```

### setImportColorTheme()

Sets the color-theme property of an import, which overrides the color-theme property of the imported style data.

#### Parameters

| Name | Description |
| --- | --- |
| **importId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Identifier of import to update. |
| **colorTheme** ColorThemeSpecification  | The color-theme properties to set. If `null` or `undefined` is provided, this function call removes the color-theme override. Note: Calling this function triggers a full reload of tiles. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setImportColorTheme("someImportId", {
    "data": "iVBORw0KGgoAA..."
});
```

### setCamera()

Sets the camera property of the style.

#### Parameters

| Name | Description |
| --- | --- |
| **camera** CameraSpecification  | The camera properties to set. Must conform to the Camera Style Specification. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setCamera({
    "camera-projection": "perspective",
});
```

### getNearClipOffset()

EXPERIMENTAL

Returns the map's near clip offset. Relevant for orthographic projection only.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current near clip offset.

#### Example

```js
map.getNearClipOffset();
```

### setNearClipOffset()

EXPERIMENTAL

Sets the map's camera near clip offset value. Relevant for orthographic projection only.

#### Parameters

| Name | Description |
| --- | --- |
| **offset** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The near clip offset to set. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setNearClipOffset(30)
```

### getCamera()

Returns the camera options specification.

#### Returns

CameraSpecification: Camera specification properties of the style.

#### Example

```js
const camera = map.getCamera();
```

### Feature state

### setFeatureState()

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 `id` attribute, which can be any number or string.

This method can only be used with sources that have a `id` attribute. The `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`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option at the time the source is defined.
-   For GeoJSON sources, using the [`generateId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#geojson-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](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling*.

#### Parameters

| Name | Description |
| --- | --- |
| **feature** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | Feature identifier. Feature objects returned from [Map#queryRenderedFeatures](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#queryrenderedfeatures) or event handlers can be used as feature identifiers. |
| **feature.id** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))  | Unique id of the feature. Can be an integer or a string, but supports string values only when the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option has been applied to the source or the string can be cast to an integer. |
| **feature.source** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The id of the vector or GeoJSON source for the feature. |
| **feature.sourceLayer** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | (optional) *For vector tile sources, `sourceLayer` is required* . |
| **state** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | A set of key-value pairs. The values should be valid JSON types. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): The map object.

#### Example

```js
// 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
        });
    }
});
```

#### Related

-   [Example: Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)
-   [Tutorial: Create interactive hover effects with Mapbox GL JS](https://docs.mapbox.com/help/tutorials/create-interactive-hover-effects-with-mapbox-gl-js/)

### removeFeatureState()

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

#### Parameters

| Name | Description |
| --- | --- |
| **feature** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | 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](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#queryrenderedfeatures) or event handlers can be used as feature identifiers. |
| **feature.id** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))?  | (optional) Unique id of the feature. Can be an integer or a string, but supports string values only when the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option has been applied to the source or the string can be cast to an integer. |
| **feature.source** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The id of the vector or GeoJSON source for the feature. |
| **feature.sourceLayer** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | (optional) For vector tile sources, `sourceLayer` is required. |
| **key** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | (optional) The key in the feature state to reset. |

#### Returns

this

#### Example

```js
// Reset the entire state object for all features
// in the `my-source` source
map.removeFeatureState({
    source: 'my-source'
});
```

```js
// 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
    });
});
```

```js
// 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');
});
```

### getFeatureState()

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 `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](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state)*.

#### Parameters

| Name | Description |
| --- | --- |
| **feature** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | Feature identifier. Feature objects returned from [Map#queryRenderedFeatures](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#queryrenderedfeatures) or event handlers can be used as feature identifiers. |
| **feature.id** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))  | Unique id of the feature. Can be an integer or a string, but supports string values only when the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option has been applied to the source or the string can be cast to an integer. |
| **feature.source** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The id of the vector or GeoJSON source for the feature. |
| **feature.sourceLayer** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)?  | (optional) *For vector tile sources, `sourceLayer` is required* . |

#### Returns

[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object): The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.

#### Example

```js
// 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
        });
    }
});
```

### resetFeatureStates()

Resets all feature state within a featureset or a style layer, setting every feature back to its default (stateless) behavior. This is the bulk equivalent of calling [Map#removeFeatureState](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#removefeaturestate) with only a source selector.

#### Parameters

| Name | Description |
| --- | --- |
| **target** [TargetDescriptor](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#targetdescriptor)  | The featureset or layer whose feature states should be reset. Pass `{featuresetId, importId?}` to target a named featureset (optionally inside a style import), or `{layerId}` to target a specific root-style layer. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): The map object.

#### Example

```js
// Reset all feature state on the 'poi' featureset inside the 'basemap' import
map.resetFeatureStates({featuresetId: 'poi', importId: 'basemap'});
```

### _selectIndoorFloor()

EXPERIMENTAL

*This API is experimental and subject to change in future versions*.

#### Parameters

| Name | Description |
| --- | --- |
| **floorId** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The id of the floor to select. |

#### Example

```js
map._selectIndoorFloor('floor-1');
```

### Lifecycle

### idle()

Returns a Boolean indicating whether the map is in idle state:

-   No camera transitions are in progress.
-   All currently requested tiles have loaded.
-   All fade/transition animations have completed.

Returns `false` if there are any camera or animation transitions in progress, 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.

If the map.repaint is set to `true`, the map will never be idle.

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether the map is idle.

#### Example

```js
const isIdle = map.idle();
```

### loaded()

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](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether the map is fully loaded.

#### Example

```js
const isLoaded = map.loaded();
```

### frameReady()

Returns a Boolean indicating whether the map is finished rendering, meaning all animations are finished.

#### Returns

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean): A Boolean indicating whether map finished rendering.

#### Example

```js
const frameReady = map.frameReady();
```

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

#### Example

```js
map.remove();
```

### triggerRepaint()

Trigger the rendering of a single frame. Use this method with custom layers to repaint the map when the layer's properties or properties associated with the layer's source change. Calling this multiple times before the next frame is rendered will still result in only a single frame being rendered.

#### Example

```js
map.triggerRepaint();
```

#### Related

-   [Example: Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/)
-   [Example: Add an animated icon to the map](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/)

### Debug features

### showTileBoundaries

Gets and sets a Boolean indicating whether the map will render an outline around each tile. These tile boundaries are useful for debugging.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

#### Example

```js
map.showTileBoundaries = true;
```

### showParseStatus

Gets and sets a Boolean indicating whether the map will render the tile ID and the status of the tile in their corner when `showTileBoundaries` is on.

The uncompressed file size of the first vector source is drawn in the top left corner of each tile, next to the tile ID.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

#### Example

```js
map.showParseStatus = true;
```

### showTerrainWireframe

Gets and sets a Boolean indicating whether the map will render a wireframe on top of the displayed terrain. Useful for debugging.

The wireframe is always red and is drawn only when terrain is active.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

#### Example

```js
map.showTerrainWireframe = true;
```

### showLayers2DWireframe

Gets and sets a Boolean indicating whether the map will render a wireframe on top of 2D layers. Useful for debugging.

The wireframe is always red and is drawn only for 2D layers.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

#### Example

```js
map.showLayers2DWireframe = true;
```

### showLayers3DWireframe

Gets and sets a Boolean indicating whether the map will render a wireframe on top of 3D layers. Useful for debugging.

The wireframe is always red and is drawn only for 3D layers.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

#### Example

```js
map.showLayers3DWireframe = true;
```

### showPadding

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

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

### showCollisionBoxes

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.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

### showOverdraw

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.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

### repaint

Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance. The map will never be idle when this option is set to `true`.

#### Type

[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)

### version

The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.

#### Type

[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)

### Camera

### getCenter()

Returns the map's geographical centerpoint.

#### Returns

[LngLat](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglat): The map's geographical centerpoint.

#### Example

```js
// Return a LngLat object such as {lng: 0, lat: 0}.
const center = map.getCenter();
// Access longitude and latitude values directly.
const {lng, lat} = map.getCenter();
```

#### Related

-   [Tutorial: Use Mapbox GL JS in a React app](https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/#store-the-new-coordinates)

### setCenter()

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

#### Parameters

| Name | Description |
| --- | --- |
| **center** [LngLatLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatlike)  | The centerpoint to set. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

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

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### panBy()

Pans the map by the specified offset.

#### Parameters

| Name | Description |
| --- | --- |
| **offset** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike)  | The `x` and `y` coordinates by which to pan the map. |
| **options** ([AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) \| null)  | An options object describing the destination and animation of the transition. We do not recommend using `options.offset` since this value will override the value of the `offset` parameter. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): `this` Returns itself to allow for method chaining.

#### Example

```js
map.panBy([-74, 38]);
```

```js
// panBy with an animation of 5 seconds.
map.panBy([-74, 38], {duration: 5000});
```

#### Related

-   [Example: Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### panTo()

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

#### Parameters

| Name | Description |
| --- | --- |
| **lnglat** [LngLatLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatlike)  | The location to pan the map to. |
| **options** ([AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) \| null)  | Options describing the destination and animation of the transition. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.panTo([-74, 38]);
```

```js
// Specify that the panTo animation should last 5000 milliseconds.
map.panTo([-74, 38], {duration: 5000});
```

#### Related

-   [Example: Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### getZoom()

Returns the map's current zoom level.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current zoom level.

#### Example

```js
map.getZoom();
```

### setZoom()

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

#### Parameters

| Name | Description |
| --- | --- |
| **zoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The zoom level to set (0-20). |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Zoom to the zoom level 5 without an animated transition
map.setZoom(5);
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend)

### zoomTo()

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

#### Parameters

| Name | Description |
| --- | --- |
| **zoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The zoom level to transition to. |
| **options** ([AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) \| null)  | Options object. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Zoom to the zoom level 5 without an animated transition
map.zoomTo(5);
// Zoom to the zoom level 8 with an animated transition
map.zoomTo(8, {
    duration: 2000,
    offset: [100, 50]
});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend)

### zoomIn()

Increases the map's zoom level by 1.

#### Parameters

| Name | Description |
| --- | --- |
| **options** ([AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) \| null)  | Options object. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// zoom the map in one level with a custom animation duration
map.zoomIn({duration: 1000});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend)

### zoomOut()

Decreases the map's zoom level by 1.

#### Parameters

| Name | Description |
| --- | --- |
| **options** ([AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) \| null)  | Options object. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// zoom the map out one level with a custom animation offset
map.zoomOut({offset: [80, 60]});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend)

### 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](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current bearing.

#### Example

```js
const bearing = map.getBearing();
```

#### Related

-   [Example: Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)

### 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})`.

#### Parameters

| Name | Description |
| --- | --- |
| **bearing** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The desired bearing. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Rotate the map to 90 degrees.
map.setBearing(90);
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### getPadding()

Returns the current padding applied around the map viewport.

#### Returns

[PaddingOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#paddingoptions): The current padding around the map viewport.

#### Example

```js
const padding = map.getPadding();
```

### setPadding()

Sets the padding in pixels around the viewport.

Equivalent to `jumpTo({padding: padding})`.

#### Parameters

| Name | Description |
| --- | --- |
| **padding** [PaddingOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#paddingoptions)  | The desired padding. Format: {left: number, right: number, top: number, bottom: number}. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// Sets a left padding of 300px, and a top padding of 50px
map.setPadding({left: 300, top: 50});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

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

#### Parameters

| Name | Description |
| --- | --- |
| **bearing** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The desired bearing. |
| **options** (EasingOptions \| null)  | Options describing the destination and animation of the transition. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.rotateTo(30);
```

```js
// rotateTo with an animation of 2 seconds.
map.rotateTo(30, {duration: 2000});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### resetNorth()

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

#### Parameters

| Name | Description |
| --- | --- |
| **options** (EasingOptions \| null)  | Options describing the destination and animation of the transition. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// resetNorth with an animation of 2 seconds.
map.resetNorth({duration: 2000});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### resetNorthPitch()

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

#### Parameters

| Name | Description |
| --- | --- |
| **options** (EasingOptions \| null)  | Options describing the destination and animation of the transition. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// resetNorthPitch with an animation of 2 seconds.
map.resetNorthPitch({duration: 2000});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### snapToNorth()

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

#### Parameters

| Name | Description |
| --- | --- |
| **options** (EasingOptions \| null)  | Options describing the destination and animation of the transition. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// snapToNorth with an animation of 2 seconds.
map.snapToNorth({duration: 2000});
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### getPitch()

Returns the map's current [pitch](https://docs.mapbox.com/help/glossary/camera/) (tilt).

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current pitch, measured in degrees away from the plane of the screen.

#### Example

```js
const pitch = map.getPitch();
```

### setPitch()

Sets the map's [pitch](https://docs.mapbox.com/help/glossary/camera/) (tilt). Equivalent to `jumpTo({pitch: pitch})`.

#### Parameters

| Name | Description |
| --- | --- |
| **pitch** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The pitch to set, measured in degrees away from the plane of the screen (0-60). |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// setPitch with an animation of 2 seconds.
map.setPitch(80, {duration: 2000});
```

#### Fires

[Map.event:pitchstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchstart), [Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### getVerticalFieldOfView()

EXPERIMENTAL

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

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current vertical field of view, measured in degrees.

#### Example

```js
const verticalFieldOfView = map.getVerticalFieldOfView();
```

### setVerticalFieldOfView()

EXPERIMENTAL

Sets the map's vertical field of view, measured in degrees. Equivalent to `jumpTo({fov})`.

#### Parameters

| Name | Description |
| --- | --- |
| **fov** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | The vertical field of view to set, measured in degrees (0.01-60). |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.setVerticalFieldOfView(30);
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### getHorizontalFieldOfView()

EXPERIMENTAL

Returns the map's current horizontal field of view, measured in degrees. This value is derived from the vertical field of view and the map's aspect ratio, and is read-only.

#### Returns

[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number): The map's current horizontal field of view, measured in degrees.

#### Example

```js
const horizontalFieldOfView = map.getHorizontalFieldOfView();
```

### cameraForBounds()

Returns a [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) object for the highest zoom level up to and including `Map#getMaxZoom()` that fits the bounds in the viewport at the specified bearing.

#### Parameters

| Name | Description |
| --- | --- |
| **bounds** [LngLatBoundsLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatboundslike)  | Calculate the center for these bounds in the viewport and use the highest zoom level up to and including `Map#getMaxZoom()` that fits in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0. |
| **options** ([CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) \| null)  | Options object. |
| **options.bearing** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `0`) | Desired map bearing at end of animation, in degrees. |
| **options.maxZoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?  | The maximum zoom level to allow when the camera would transition to the specified bounds. |
| **options.offset** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike) (default `[0,0]`) | The center of the given bounds relative to the map's center, measured in pixels. |
| **options.padding** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [PaddingOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#paddingoptions))?  | The amount of padding in pixels to add to the given bounds. |
| **options.pitch** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `0`) | Desired map pitch at end of animation, in degrees. |

#### Returns

([CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) \| void): If map is able to fit to provided bounds, returns `CameraOptions` with `center` , `zoom` , and `bearing` . If map is unable to fit, method will warn and return undefined.

#### Example

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

### Querying features

### queryTerrainElevation()

Queries the currently loaded data for elevation at a geographical location. The elevation is returned in `meters` relative to mean sea-level. Returns `null` if `terrain` is disabled or if terrain data for the location hasn't been loaded yet.

In order to guarantee that the terrain data is loaded ensure that the geographical location is visible and wait for the `idle` event to occur.

#### Parameters

| Name | Description |
| --- | --- |
| **lnglat** [LngLatLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatlike)  | The geographical location at which to query. |
| **options** [ElevationQueryOptions](#elevationqueryoptions)?  | Options object. |
| **options.exaggerated** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `true`) | When `true` returns the terrain elevation with the value of `exaggeration` from the style already applied. When `false` , returns the raw value of the underlying data without styling applied. |

#### Returns

([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| null): The elevation in meters.

#### Example

```js
const coordinate = [-122.420679, 37.772537];
const elevation = map.queryTerrainElevation(coordinate);
```

#### Related

-   [Example: Query terrain elevation](https://docs.mapbox.com/mapbox-gl-js/example/query-terrain-elevation/)

### fitBounds()

Pans and zooms the map to contain its visible area within the specified geographical bounds. If a padding is set on the map, the bounds are fit to the inset.

#### Parameters

| Name | Description |
| --- | --- |
| **bounds** [LngLatBoundsLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#lnglatboundslike)  | Center these bounds in the viewport and use the highest zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport. |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?  | Options supports all properties from [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) and [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) in addition to the fields below. |
| **options.bearing** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `0`) | Desired map bearing at end of animation, in degrees. |
| **options.easing** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?  | An easing function for the animated transition. See [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **options.linear** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `false`) | If `true` , the map transitions using [Map#easeTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#easeto) . If `false` , the map transitions using [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto) . See those functions and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) for information about options available. |
| **options.maxZoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?  | The maximum zoom level to allow when the map view transitions to the specified bounds. |
| **options.offset** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike) (default `[0,0]`) | The center of the given bounds relative to the map's center, measured in pixels. |
| **options.padding** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [PaddingOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#paddingoptions))?  | The amount of padding in pixels to add to the given bounds. |
| **options.pitch** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `0`) | Desired map pitch at end of animation, in degrees. |
| **eventData** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
const bbox = [[-79, 43], [-73, 45]];
map.fitBounds(bbox, {
    padding: {top: 10, bottom:25, left: 15, right: 5}
});
```

#### Related

-   [Example: Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### fitScreenCoordinates()

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.

#### Parameters

| Name | Description |
| --- | --- |
| **p0** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike)  | First point on screen, in pixel coordinates. |
| **p1** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike)  | Second point on screen, in pixel coordinates. |
| **bearing** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)  | Desired map bearing at end of animation, in degrees. |
| **options** (EasingOptions \| null)  | Options object. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **options.easing** [Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)?  | An easing function for the animated transition. See [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **options.linear** [boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean) (default `false`) | If `true` , the map transitions using [Map#easeTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#easeto) . If `false` , the map transitions using [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto) . See those functions and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) for information about options available. |
| **options.maxZoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?  | The maximum zoom level to allow when the map view transitions to the specified bounds. |
| **options.offset** [PointLike](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/geography/#pointlike) (default `[0,0]`) | The center of the given bounds relative to the map's center, measured in pixels. |
| **options.padding** ([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [PaddingOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#paddingoptions))?  | The amount of padding in pixels to add to the given bounds. |
| **options.pitch** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `0`) | Desired map pitch at end of animation, in degrees. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

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

#### Related

-   Used by [BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend)

### jumpTo()

Changes any combination of center, zoom, bearing, and pitch, without an animated transition. The map will retain its current values for any details not specified in `options`.

#### Parameters

| Name | Description |
| --- | --- |
| **options** [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions)  | Options object. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// 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
});
```

#### Related

-   [Example: Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/)
-   [Example: Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:pitchstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchstart), [Map.event:rotate](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:rotate), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:pitch](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitch), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend), [Map.event:pitchend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchend)

### getFreeCameraOptions()

Returns position and orientation of the camera entity.

This method is not supported for projections other than mercator.

#### Returns

[FreeCameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#freecameraoptions): The camera state.

#### Example

```js
const camera = map.getFreeCameraOptions();

const position = [138.72649, 35.33974];
const altitude = 3000;

camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
camera.lookAtPoint([138.73036, 35.36197]);

map.setFreeCameraOptions(camera);
```

### setFreeCameraOptions()

`FreeCameraOptions` provides more direct access to the underlying camera entity. For backwards compatibility the state set using this API must be representable with `CameraOptions` as well. Parameters are clamped into a valid range or discarded as invalid if the conversion to the pitch and bearing presentation is ambiguous. For example orientation can be invalid if it leads to the camera being upside down, the quaternion has zero length, or the pitch is over the maximum pitch limit.

This method is not supported for projections other than mercator.

#### Parameters

| Name | Description |
| --- | --- |
| **options** [FreeCameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#freecameraoptions)  | `FreeCameraOptions` object. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
const camera = map.getFreeCameraOptions();

const position = [138.72649, 35.33974];
const altitude = 3000;

camera.position = mapboxgl.MercatorCoordinate.fromLngLat(position, altitude);
camera.lookAtPoint([138.73036, 35.36197]);

map.setFreeCameraOptions(camera);
```

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:pitchstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchstart), [Map.event:rotate](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:rotate), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:pitch](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitch), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend), [Map.event:pitchend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchend)

### easeTo()

Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition between old and new values. The map will retain its current values for any details not specified in `options`.

Note: The transition will happen instantly if the user has enabled the `reduced motion` accessibility feature enabled in their operating system, unless `options` includes `essential: true`.

#### Parameters

| Name | Description |
| --- | --- |
| **options** EasingOptions  | Options describing the destination and animation of the transition. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) and [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) . |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): `this` Returns itself to allow for method chaining.

#### Example

```js
// Ease with default options to null island for 5 seconds.
map.easeTo({center: [0, 0], zoom: 9, duration: 5000});
```

```js
// Using easeTo options.
map.easeTo({
    center: [0, 0],
    zoom: 9,
    speed: 0.2,
    curve: 1,
    duration: 5000,
    easing(t) {
        return t;
    }
});
```

#### Related

-   [Example: Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:pitchstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchstart), [Map.event:rotate](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:rotate), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:pitch](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitch), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend), [Map.event:pitchend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchend)

### flyTo()

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 their bearings even after traversing a great distance.

If a user has the `reduced motion` accessibility feature enabled in their operating system, the animation will be skipped and this will behave equivalently to `jumpTo`, unless 'options' includes `essential: true`.

#### Parameters

| Name | Description |
| --- | --- |
| **options** [Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)  | Options describing the destination and animation of the transition. Accepts [CameraOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#cameraoptions) , [AnimationOptions](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/properties/#animationoptions) , and the following additional options. |
| **options.curve** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `1.42`) | The zooming "curve" that will occur along the flight path. A high value maximizes zooming for an exaggerated animation, while a low value minimizes zooming for an effect closer to [Map#easeTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#easeto) . 1.42 is the average value selected by participants in the user study discussed in [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf) . A value of `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A value of 1 would produce a circular motion. If `options.minZoom` is specified, this option will be ignored. |
| **options.maxDuration** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?  | The animation's maximum duration, measured in milliseconds. If duration exceeds maximum duration, it resets to 0. |
| **options.minZoom** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?  | The zero-based zoom level at the peak of the flight path. If this option is specified, `options.curve` will be ignored. |
| **options.screenSpeed** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)?  | The average speed of the animation measured in screenfuls per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored. |
| **options.speed** [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) (default `1.2`) | The average speed of the animation defined in relation to `options.curve` . A speed of 1.2 means that the map appears to move along the flight path by 1.2 times `options.curve` screenfuls every second. A *screenful* is the map's visible span. It does not correspond to a fixed physical distance, but varies by zoom level. |
| **eventData** ([Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object) \| null)  | Additional properties to be added to event objects of events triggered by this method. |

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
// fly with default options to null island
map.flyTo({center: [0, 0], zoom: 9});
// using flyTo options
map.flyTo({
    center: [0, 0],
    zoom: 9,
    speed: 0.2,
    curve: 1,
    easing(t) {
        return t;
    }
});
```

#### Related

-   [Example: Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/)
-   [Example: Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/)
-   [Example: Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/)

#### Fires

[Map.event:movestart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:movestart), [Map.event:zoomstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomstart), [Map.event:pitchstart](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchstart), [Map.event:move](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:move), [Map.event:zoom](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoom), [Map.event:rotate](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:rotate), [Map.event:pitch](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitch), [Map.event:moveend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:moveend), [Map.event:zoomend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:zoomend), [Map.event:pitchend](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:pitchend)

### stop()

Stops any animated transition underway.

#### Returns

[Map](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map): Returns itself to allow for method chaining.

#### Example

```js
map.stop();
```

## Events

### resize

Fired immediately after the map has been resized.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// immediately after the map has been resized.
map.on('resize', () => {
    console.log('A resize event occurred.');
});
```

### idle

Fired after the last frame rendered before the map enters an "idle" state:

-   No camera transitions are in progress
-   All currently requested tiles have loaded
-   All fade/transition animations have completed.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just before the map enters an "idle" state.
map.on('idle', () => {
    console.log('A idle event occurred.');
});
```

### remove

Fired immediately after the map has been removed with [Map.event:remove](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:remove).

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just after the map is removed.
map.on('remove', () => {
    console.log('A remove event occurred.');
});
```

### mousedown

Fired when a pointing device (usually a mouse) is pressed within the map.

**Note:** This event is compatible with the optional `layerId` parameter. If `layerId` is included as the second argument in [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), the event listener will fire only when the the cursor is pressed while inside a visible portion of the specifed layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('mousedown', () => {
    console.log('A mousedown event has occurred.');
});
```

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener for a specific layer
map.on('mousedown', 'poi-label', () => {
    console.log('A mousedown event has occurred on a visible portion of the poi-label layer.');
});
```

#### Related

-   [Example: Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### mouseup

Fired when a pointing device (usually a mouse) is released within the map.

**Note:** This event is compatible with the optional `layerId` parameter. If `layerId` is included as the second argument in [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), the event listener will fire only when the the cursor is released while inside a visible portion of the specifed layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('mouseup', () => {
    console.log('A mouseup event has occurred.');
});
```

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener for a specific layer
map.on('mouseup', 'poi-label', () => {
    console.log('A mouseup event has occurred on a visible portion of the poi-label layer.');
});
```

#### Related

-   [Example: Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)
-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### mouseover

Fired when a pointing device (usually a mouse) is moved within the map. As you move the cursor across a web page containing a map, the event will fire each time it enters the map or any child elements.

**Note:** This event is compatible with the optional `layerId` parameter. If `layerId` is included as the second argument in [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), the event listener will fire only when the the cursor is moved inside a visible portion of the specifed layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('mouseover', () => {
    console.log('A mouseover event has occurred.');
});
```

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener for a specific layer
map.on('mouseover', 'poi-label', () => {
    console.log('A mouseover event has occurred on a visible portion of the poi-label layer.');
});
```

#### Related

-   [Example: Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)
-   [Example: Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)
-   [Example: Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)

### mousemove

Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map. As you move the cursor across the map, the event will fire every time the cursor changes position within the map.

**Note:** This event is compatible with the optional `layerId` parameter. If `layerId` is included as the second argument in [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), the event listener will fire only when the the cursor is inside a visible portion of the specified layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('mousemove', () => {
    console.log('A mousemove event has occurred.');
});
```

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener for a specific layer
map.on('mousemove', 'poi-label', () => {
    console.log('A mousemove event has occurred on a visible portion of the poi-label layer.');
});
```

#### Related

-   [Example: Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)
-   [Example: Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)
-   [Example: Display a popup on over](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)

### preclick

Triggered when a click event occurs and is fired before the click event. Primarily implemented to ensure closeOnClick for pop-ups is fired before any other listeners.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

### click

Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.

**Note:** This event is compatible with the optional `layerId` parameter. If `layerId` is included as the second argument in [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), the event listener will fire only when the point that is pressed and released contains a visible portion of the specifed layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('click', (e) => {
    console.log(`A click event has occurred at ${e.lngLat}`);
});
```

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener for a specific layer
map.on('click', 'poi-label', (e) => {
    console.log(`A click event has occurred on a visible portion of the poi-label layer at ${e.lngLat}`);
});
```

#### Related

-   [Example: Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)
-   [Example: Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)

### dblclick

Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on the map in rapid succession.

**Note:** This event is compatible with the optional `layerId` parameter. If `layerId` is included as the second argument in [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on), the event listener will fire only when the point that is clicked twice contains a visible portion of the specifed layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('dblclick', (e) => {
    console.log(`A dblclick event has occurred at ${e.lngLat}`);
});
```

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener for a specific layer
map.on('dblclick', 'poi-label', (e) => {
    console.log(`A dblclick event has occurred on a visible portion of the poi-label layer at ${e.lngLat}`);
});
```

### mouseenter

Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from outside that layer or outside the map canvas.

**Important:** This event can only be listened for when [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on) includes three arguments, where the second argument specifies the desired layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener
map.on('mouseenter', 'water', () => {
    console.log('A mouseenter event occurred on a visible portion of the water layer.');
});
```

#### Related

-   [Example: Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/)
-   [Example: Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)

### mouseleave

Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer or moves from the specified layer to outside the map canvas.

**Note:** To detect when the mouse leaves the canvas, independent of layer, use [Map.event:mouseout](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:mouseout) instead.

**Important:** This event can only be listened for when [Map#on](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#on) includes three arguments, where the second argument specifies the desired layer.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the pointing device leaves
// a visible portion of the specified layer.
map.on('mouseleave', 'water', () => {
    console.log('A mouseleave event occurred.');
});
```

#### Related

-   [Example: Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)
-   [Example: Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)

### mouseout

Fired when a point device (usually a mouse) leaves the map's canvas.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the pointing device leaves
// the map's canvas.
map.on('mouseout', () => {
    console.log('A mouseout event occurred.');
});
```

### contextmenu

Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.

#### Type

[MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the right mouse button is
// pressed within the map.
map.on('contextmenu', () => {
    console.log('A contextmenu event occurred.');
});
```

### wheel

Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map.

#### Type

[MapWheelEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapwheelevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when a wheel event occurs within the map.
map.on('wheel', () => {
    console.log('A wheel event occurred.');
});
```

### touchstart

Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map.

#### Type

[MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when a `touchstart` event occurs within the map.
map.on('touchstart', () => {
    console.log('A touchstart event occurred.');
});
```

#### Related

-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### touchend

Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map.

#### Type

[MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent)

#### Example

```js
// Initialize the map.
const map = new mapboxgl.Map({});
// Set an event listener that fires when a `touchend` event occurs within the map.
map.on('touchend', () => {
    console.log('A touchend event occurred.');
});
```

#### Related

-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### touchmove

Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map.

#### Type

[MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent)

#### Example

```js
// Initialize the map.
const map = new mapboxgl.Map({});
// Set an event listener that fires when a touchmove event occurs within the map.
map.on('touchmove', () => {
    console.log('A touchmove event occurred.');
});
```

#### Related

-   [Example: Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)

### touchcancel

Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map.

#### Type

[MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent)

#### Example

```js
// Initialize the map.
const map = new mapboxgl.Map({});
// Set an event listener that fires when a `touchcancel` event occurs within the map.
map.on('touchcancel', () => {
    console.log('A touchcancel event occurred.');
});
```

### movestart

Fired just before the map begins a transition from one view to another, as the result of either user interaction or methods such as [Map#jumpTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#jumpto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map.
const map = new mapboxgl.Map({});
// Set an event listener that fires just before the map begins a transition from one view to another.
map.on('movestart', () => {
    console.log('A movestart` event occurred.');
});
```

### move

Fired repeatedly during an animated transition from one view to another, as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map.
const map = new mapboxgl.Map({});
// Set an event listener that fires repeatedly during an animated transition.
map.on('move', () => {
    console.log('A move event occurred.');
});
```

#### Related

-   [Example: Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)
-   [Example: Filter features within map view](https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)

### moveend

Fired just after the map completes a transition from one view to another, as the result of either user interaction or methods such as [Map#jumpTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#jumpto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just after the map completes a transition.
map.on('moveend', () => {
    console.log('A moveend event occurred.');
});
```

#### Related

-   [Example: Play map locations as a slideshow](https://www.mapbox.com/mapbox-gl-js/example/playback-locations/)
-   [Example: Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)
-   [Example: Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)

### dragstart

Fired when a "drag to pan" interaction starts. See [DragPanHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragpanhandler).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when a "drag to pan" interaction starts.
map.on('dragstart', () => {
    console.log('A dragstart event occurred.');
});
```

### drag

Fired repeatedly during a "drag to pan" interaction. See [DragPanHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragpanhandler).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// repeatedly during a "drag to pan" interaction.
map.on('drag', () => {
    console.log('A drag event occurred.');
});
```

### dragend

Fired when a "drag to pan" interaction ends. See [DragPanHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragpanhandler).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when a "drag to pan" interaction ends.
map.on('dragend', () => {
    console.log('A dragend event occurred.');
});
```

#### Related

-   [Example: Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/)

### zoomstart

Fired just before the map begins a transition from one zoom level to another, as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just before a zoom transition starts.
map.on('zoomstart', () => {
    console.log('A zoomstart event occurred.');
});
```

### zoom

Fired repeatedly during an animated transition from one zoom level to another, as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// repeatedly during a zoom transition.
map.on('zoom', () => {
    console.log('A zoom event occurred.');
});
```

#### Related

-   [Example: Update a choropleth layer by zoom level](https://www.mapbox.com/mapbox-gl-js/example/updating-choropleth/)

### zoomend

Fired just after the map completes a transition from one zoom level to another as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto). The zoom transition will usually end before rendering is finished, so if you need to wait for rendering to finish, use the [Map.event:idle](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map.event:idle) event instead.

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just after a zoom transition finishes.
map.on('zoomend', () => {
    console.log('A zoomend event occurred.');
});
```

### rotatestart

Fired when a "drag to rotate" interaction starts. See [DragRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragrotatehandler).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just before a "drag to rotate" interaction starts.
map.on('rotatestart', () => {
    console.log('A rotatestart event occurred.');
});
```

### rotate

Fired repeatedly during a "drag to rotate" interaction. See [DragRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragrotatehandler).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// repeatedly during "drag to rotate" interaction.
map.on('rotate', () => {
    console.log('A rotate event occurred.');
});
```

### rotateend

Fired when a "drag to rotate" interaction ends. See [DragRotateHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#dragrotatehandler).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just after a "drag to rotate" interaction ends.
map.on('rotateend', () => {
    console.log('A rotateend event occurred.');
});
```

### pitchstart

Fired whenever the map's pitch (tilt) begins a change as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto) .

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just before a pitch (tilt) transition starts.
map.on('pitchstart', () => {
    console.log('A pitchstart event occurred.');
});
```

### pitch

Fired repeatedly during the map's pitch (tilt) animation between one state and another as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// repeatedly during a pitch (tilt) transition.
map.on('pitch', () => {
    console.log('A pitch event occurred.');
});
```

### pitchend

Fired immediately after the map's pitch (tilt) finishes changing as the result of either user interaction or methods such as [Map#flyTo](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#flyto).

#### Type

([MapMouseEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapmouseevent) \| [MapTouchEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#maptouchevent))

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just after a pitch (tilt) transition ends.
map.on('pitchend', () => {
    console.log('A pitchend event occurred.');
});
```

### boxzoomstart

Fired when a "box zoom" interaction starts. See [BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler).

#### Type

[MapBoxZoomEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapboxzoomevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just before a "box zoom" interaction starts.
map.on('boxzoomstart', () => {
    console.log('A boxzoomstart event occurred.');
});
```

### boxzoomend

Fired when a "box zoom" interaction ends. See [BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler).

#### Type

[MapBoxZoomEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapboxzoomevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// just after a "box zoom" interaction ends.
map.on('boxzoomend', () => {
    console.log('A boxzoomend event occurred.');
});
```

### boxzoomcancel

Fired when the user cancels a "box zoom" interaction, or when the bounding box does not meet the minimum size threshold. See [BoxZoomHandler](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/handlers/#boxzoomhandler).

#### Type

[MapBoxZoomEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapboxzoomevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// the user cancels a "box zoom" interaction.
map.on('boxzoomcancel', () => {
    console.log('A boxzoomcancel event occurred.');
});
```

### load

Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the map has finished loading.
map.on('load', () => {
    console.log('A load event occurred.');
});
```

#### Related

-   [Example: Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)
-   [Example: Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/)
-   [Example: Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)

### renderstart

Fired whenever the rendering process of the map is started. This event can be used in pair with the "render" event, to measure the time spent on the CPU during the rendering of a single frame.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the map begins rendering.
map.on('renderstart', () => {
    console.log('A renderstart event occurred.');
});
```

### render

Fired whenever the map is drawn to the screen, as the result of:

-   a change to the map's position, zoom, pitch, or bearing
-   a change to the map's style
-   a change to a GeoJSON source
-   the loading of a vector tile, GeoJSON file, glyph, or sprite.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// whenever the map is drawn to the screen.
map.on('render', () => {
    console.log('A render event occurred.');
});
```

### error

Fired when an error occurs. This is Mapbox GL JS's primary error reporting mechanism. We use an event instead of `throw` to better accommodate asyncronous operations. If no listeners are bound to the `error` event, the error will be printed to the console.

#### Properties

| Name | Description |
| --- | --- |
| **message** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | Error message. |

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when an error occurs.
map.on('error', () => {
    console.log('A error event occurred.');
});
```

### webglcontextlost

Fired when the WebGL context is lost.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the WebGL context is lost.
map.on('webglcontextlost', () => {
    console.log('A webglcontextlost event occurred.');
});
```

### webglcontextrestored

Fired when the WebGL context is restored.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the WebGL context is restored.
map.on('webglcontextrestored', () => {
    console.log('A webglcontextrestored event occurred.');
});
```

### data

Fired when any map data loads or changes. See [MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent) for more information.

#### Type

[MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when map data loads or changes.
map.on('data', () => {
    console.log('A data event occurred.');
});
```

#### Related

-   [Example: Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)

### styledata

Fired when the map's style loads or changes. See [MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent) for more information.

#### Type

[MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the map's style loads or changes.
map.on('styledata', () => {
    console.log('A styledata event occurred.');
});
```

### sourcedata

Fired when one of the map's sources loads or changes, including if a tile belonging to a source loads or changes. See [MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent) for more information.

#### Type

[MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when one of the map's sources loads or changes.
map.on('sourcedata', () => {
    console.log('A sourcedata event occurred.');
});
```

### dataloading

Fired when any map data (style, source, tile, etc) begins loading or changing asynchronously. All `dataloading` events are followed by a `data` or `error` event. See [MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent) for more information.

#### Type

[MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when any map data begins loading
// or changing asynchronously.
map.on('dataloading', () => {
    console.log('A dataloading event occurred.');
});
```

### styledataloading

Fired when the map's style begins loading or changing asynchronously. All `styledataloading` events are followed by a `styledata` or `error` event. See [MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent) for more information.

#### Type

[MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the map's style begins loading or
// changing asynchronously.
map.on('styledataloading', () => {
    console.log('A styledataloading event occurred.');
});
```

### sourcedataloading

Fired when one of the map's sources begins loading or changing asynchronously. All `sourcedataloading` events are followed by a `sourcedata` or `error` event. See [MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent) for more information.

#### Type

[MapDataEvent](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/events/#mapdataevent)

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the map's sources begin loading or
// changing asynchronously.
map.on('sourcedataloading', () => {
    console.log('A sourcedataloading event occurred.');
});
```

### styleimagemissing

Fired when an icon or pattern needed by the style is missing. The missing image can be added with [Map#addImage](https://docs.mapbox.com/mapbox-gl-js/mapbox-gl-js/api/map/#map#addimage) within this event listener callback to prevent the image from being skipped. This event can be used to dynamically generate icons and patterns.

#### Properties

| Name | Description |
| --- | --- |
| **id** [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)  | The id of the missing image. |

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when an icon or pattern is missing.
map.on('styleimagemissing', () => {
    console.log('A styleimagemissing event occurred.');
});
```

#### Related

-   [Example: Generate and add a missing icon to the map](https://mapbox.com/mapbox-gl-js/example/add-image-missing-generated/)

### style.load

Fired immediately after all style resources have been downloaded and the first visually complete rendering of the base style has occurred.

In general, it's recommended to add custom sources and layers after this event. This approach allows for a more efficient initialization and faster rendering of the added layers.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the map has finished loading.
map.on('style.load', () => {
    console.log('A style load event occurred.');
});
```

#### Related

-   [Example: Persist layers when switching base style](https://www.mapbox.com/mapbox-gl-js/example/style-switch)

### style.import.load

Fired immediately after imported style resources have been downloaded and the first visually complete rendering of the base style extended with the imported style has occurred.

#### Example

```js
// Initialize the map
const map = new mapboxgl.Map({});
// Set an event listener that fires
// when the style import has finished loading.
map.on('style.import.load', () => {
    console.log('A style import load event occurred.');
});
```

## Related

-   [Example: Display a map on a webpage](https://docs.mapbox.com/mapbox-gl-js/example/simple-map/)
-   [Example: Display a map with a custom style](https://docs.mapbox.com/mapbox-gl-js/example/custom-style-id/)
-   [Example: Check if Mapbox GL JS is supported](https://docs.mapbox.com/mapbox-gl-js/example/check-for-support/)