### Install Additional Linux Dependencies for Canvas/GL Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Install these if prebuilt binaries for canvas and gl are not available on Linux. ```bash sudo apt-get install python-is-python3 pkg-config pixman-1 libpixman-1-dev libcairo2-dev libpango1.0-dev libgif-dev ``` -------------------------------- ### Map Initialization Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Example of how to initialize a new Map instance with various configuration options. ```APIDOC ## Map Initialization ### Description Instantiates a new Map object, which represents the map on your page. You must specify a `container` element and can configure various aspects of the map through `MapOptions`. ### Parameters * **options** (MapOptions) - Required - An object containing map configuration options. * **container** (string | HTMLElement) - Required - The ID of the HTML element or the HTML element itself that will contain the map. * **center** (LngLatLike) - Optional - The initial center of the map. Defaults to `[0, 0]`. * **zoom** (number) - Optional - The initial zoom level of the map. Defaults to `0`. * **style** (Style | string) - Optional - The initial style of the map. Can be a style object, a URL to a style, or a style name. Defaults to `MapLibre.Map.DEFAULT_STYLE`. * **hash** (boolean) - Optional - If true, the map's hash will be updated when the map's `center` and `zoom` change. Defaults to `false`. * **transformRequest** (TransformRequestFunction) - Optional - A function that allows you to modify outgoing requests for resources like tiles and sprites. ### Example ```javascript let map = new Map({ container: 'map', center: [-122.420679, 37.772537], zoom: 13, style: style_object, hash: true, 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 } } } }); ``` ``` -------------------------------- ### Install Node Module Dependencies Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Install all Node.js module dependencies for the project after cloning the repository. ```bash cd maplibre-gl-js && npm install ``` -------------------------------- ### Install Node.js using Homebrew Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Install the required Node.js version using Homebrew on macOS. ```bash brew install node ``` -------------------------------- ### Basic Vertex Shader Source Example Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/CustomRenderMethodInput A simplified example of vertex shader source code, demonstrating the use of MapLibre's `projectTile` function with provided shader data. Suitable for custom layers needing basic projection. ```javascript const vertexSource = `#version 300 es ${shaderData.vertexShaderPrelude} ${shaderData.define} in vec2 a_pos; void main() { gl_Position = projectTile(a_pos); }`; ``` -------------------------------- ### Install Node.js using NVM Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Installs the Node.js version specified in the .nvmrc file within the project. ```bash nvm install ``` -------------------------------- ### Example Usage of CameraOptions Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/CameraOptions Demonstrates how to set the map's initial perspective using CameraOptions. ```javascript let map = new Map({ container: 'map', style: 'https://demotiles.maplibre.org/style.json', center: [-73.5804, 45.53483], pitch: 60, bearing: -60, zoom: 10 }); ``` -------------------------------- ### Install NVM (Node Version Manager) Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Installs NVM, a script to manage multiple Node.js versions, using a curl command. ```bash curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash ``` -------------------------------- ### Custom Shader Vertex Source Example Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/CustomRenderMethodInput Example of constructing vertex shader source code using shader data, including prelude and defines. This is useful for custom shaders that need MapLibre's projection functions. ```javascript const vertexSource = `#version 300 es ${shaderData.vertexShaderPrelude} ${shaderData.define} in vec2 a_pos; void main() { gl_Position = projectTile(a_pos); #ifdef GLOBE // Do globe-specific things #endif }`; ``` -------------------------------- ### Install Windows Headless-GL Dependencies Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Copies necessary DLL files for headless-gl to the system32 directory on Windows. ```bash copy node_modules/headless-gl/deps/windows/dll/x64/*.dll c:\windows\system32 ``` -------------------------------- ### Install Linux Build Dependencies Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Installs essential build tools and libraries required for MapLibre GL JS development on Linux and GitHub Codespaces. ```bash sudo apt-get update && sudo apt-get install build-essential git glew-utils libglew-dev libxi-dev default-jre default-jdk xvfb ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Install the Xcode Command Line Tools package required for development on macOS. ```bash xcode-select --install ``` -------------------------------- ### MapDataEvent Example Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapDataEvent Example of how to listen for the `sourcedata` event, which is an example of MapDataEvent. ```APIDOC ## Example ```javascript // The sourcedata event is an example of MapDataEvent. // Set up an event listener on the map. map.on('sourcedata', (e) => { if (e.isSourceLoaded) { // Do something when the source has finished loading } }); ``` ``` -------------------------------- ### Custom Layer Implementation Example Source: https://maplibre.org/maplibre-gl-js/docs/API/interfaces/CustomLayerInterface An example of a custom layer implemented as an ES6 class, demonstrating the `id`, `type`, `renderingMode`, `onAdd`, and `render` methods. ```APIDOC ## Custom Layer Implementation Example This example shows how to implement a custom layer using an ES6 class. ```javascript class NullIslandLayer { constructor() { this.id = 'null-island'; this.type = 'custom'; this.renderingMode = '2d'; } onAdd(map: maplibregl.Map, gl: WebGLRenderingContext | WebGL2RenderingContext) { const vertexSource = ` uniform mat4 u_matrix; void main() { gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0); gl_PointSize = 20.0; }`; const fragmentSource = ` void main() { fragColor = vec4(1.0, 0.0, 0.0, 1.0); }`; const vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vertexSource); gl.compileShader(vertexShader); const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fragmentSource); gl.compileShader(fragmentShader); this.program = gl.createProgram(); gl.attachShader(this.program, vertexShader); gl.attachShader(this.program, fragmentShader); gl.linkProgram(this.program); } render({ gl, modelViewProjectionMatrix: matrix }: { gl: WebGLRenderingContext | WebGL2RenderingContext; modelViewProjectionMatrix: Float32Array; }) { gl.useProgram(this.program); gl.uniformMatrix4fv(gl.getUniformLocation(this.program, "u_matrix"), false, matrix); gl.drawArrays(gl.POINTS, 0, 1); } } map.on('load', () => { map.addLayer(new NullIslandLayer()); }); ``` ``` -------------------------------- ### Install MapLibre GL JS via npm Source: https://maplibre.org/maplibre-gl-js/docs Use npm to install the MapLibre GL JS package into your project. ```bash npm install maplibre-gl ``` -------------------------------- ### RasterDEMTileSource Example Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/RasterDEMTileSource Example of how to add a RasterDEMTileSource to a map. ```APIDOC ## RasterDEMTileSource Example ### Description Example of how to add a RasterDEMTileSource to a map. ### Code ```javascript map.addSource('raster-dem-source', { type: 'raster-dem', url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json', tileSize: 256 }); ``` ``` -------------------------------- ### Install Dependencies for node-canvas Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Install system-level dependencies required for node-canvas on macOS. ```bash brew install pkg-config cairo pango libpng jpeg giflib librsvg ``` -------------------------------- ### Install Build Dependencies for Canvas/GL Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Run this command in `node_modules/canvas` and `node_modules/gl` if canvas.node or webgl.node cannot be found on Apple Silicon machines. ```bash npm install --build-from-source ``` -------------------------------- ### LngLatBoundsLike Examples Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/LngLatBoundsLike Demonstrates the different ways to represent bounding box coordinates using the LngLatBoundsLike type. ```javascript let v1 = new LngLatBounds( new LngLat(-73.9876, 40.7661), new LngLat(-73.9397, 40.8002) ); ``` ```javascript let v2 = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]) ``` ```javascript let v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]]; ``` -------------------------------- ### Example Usage of PaddingOptions Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/PaddingOptions Demonstrates how to use the PaddingOptions type with specific pixel values for each edge when fitting bounds. ```APIDOC ## Example 1: Specific Padding for Each Edge ```javascript let bbox = [[-79, 43], [-73, 45]]; map.fitBounds(bbox, { padding: {top: 10, bottom:25, left: 15, right: 5} }); ``` ``` -------------------------------- ### Initialize a Map Source: https://maplibre.org/maplibre-gl-js/docs/examples Basic map initialization in an HTML element. This example uses a standard style. ```javascript const map = new maplibregl.Map({ container: 'map', style: 'https://api.maptiler.com/maps/streets/style.json?key=YOUR_MAPTILER_API_KEY', center: [-0.1278, 51.5074], zoom: 10 }); ``` -------------------------------- ### rotatestart Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType Fired when a "drag to rotate" interaction starts. See DragRotateHandler. ```APIDOC ## rotatestart ### Description Fired when a "drag to rotate" interaction starts. See DragRotateHandler. ### Event Type `MapLibreEvent` ``` -------------------------------- ### dragstart Event Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType Fired when a "drag to pan" interaction starts. See DragPanHandler. ```APIDOC ## dragstart > **dragstart** : `MapLibreEvent`<`MouseEvent` | `TouchEvent` | `undefined`> Defined in: ui/events.ts:385 Fired when a "drag to pan" interaction starts. See DragPanHandler. ``` -------------------------------- ### PointLike Examples Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/PointLike Demonstrates creating PointLike values using both Point objects and arrays of numbers. ```typescript let p1 = new Point(-77, 38); // a PointLike which is a Point let p2 = [-77, 38]; // a PointLike which is an array of two numbers ``` -------------------------------- ### Adding a Vector Tile Source with URL Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/VectorTileSource This example demonstrates how to add a vector tile source to the map using a URL to a tileset configuration. ```APIDOC ## Add Vector Tile Source with URL ### Description Adds a vector tile source to the map using a URL that points to a tileset configuration file. ### Method `map.addSource(id, options)` ### Parameters #### id (string) - A unique identifier for the source. #### options (object) - Configuration options for the source. - **type** (string) - Must be 'vector'. - **url** (string) - The URL to the tileset configuration. ### Request Example ```javascript map.addSource('some id', { type: 'vector', url: 'https://demotiles.maplibre.org/tiles/tiles.json' }); ``` ``` -------------------------------- ### Example Usage of Uniform Padding Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/PaddingOptions Demonstrates how to use the PaddingOptions type with a single number for uniform padding across all edges. ```APIDOC ## Example 2: Uniform Padding ```javascript let bbox = [[-79, 43], [-73, 45]]; map.fitBounds(bbox, { padding: 20 }); ``` ``` -------------------------------- ### CooperativeGesturesHandler Initialization Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/CooperativeGesturesHandler This example shows how to enable the CooperativeGesturesHandler when initializing a new Map instance. ```APIDOC ## Example ```javascript const map = new Map({ cooperativeGestures: true }); ``` ``` -------------------------------- ### LngLatLike Examples Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/LngLatLike Demonstrates different ways to define LngLatLike coordinates: using the LngLat class, an array, or an object with lon/lat properties. ```javascript let v1 = new LngLat(-122.420679, 37.772537); let v2 = [-122.420679, 37.772537]; let v3 = {lon: -122.420679, lat: 37.772537}; ``` -------------------------------- ### boxzoomstart Event Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType Fired when a "box zoom" interaction starts. See BoxZoomHandler. ```APIDOC ## boxzoomstart > **boxzoomstart** : `MapLibreZoomEvent` Defined in: ui/events.ts:258 Fired when a "box zoom" interaction starts. See BoxZoomHandler. ``` -------------------------------- ### Adding a Vector Tile Source with Tile URLs Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/VectorTileSource This example shows how to add a vector tile source by directly providing an array of tile URLs and specifying zoom levels. ```APIDOC ## Add Vector Tile Source with Tile URLs ### Description Adds a vector tile source to the map by specifying an array of tile URLs and optionally defining the minimum and maximum zoom levels. ### Method `map.addSource(id, options)` ### Parameters #### id (string) - A unique identifier for the source. #### options (object) - Configuration options for the source. - **type** (string) - Must be 'vector'. - **tiles** (Array) - An array of tile URL templates. - **minzoom** (number, optional) - The minimum zoom level for the source. - **maxzoom** (number, optional) - The maximum zoom level for the source. ### Request Example ```javascript map.addSource('some id', { type: 'vector', tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'], minzoom: 6, maxzoom: 14 }); ``` ``` -------------------------------- ### Implement IControl Interface Source: https://maplibre.org/maplibre-gl-js/docs/API/interfaces/IControl Example of a custom control implementing the IControl interface. It creates a 'Hello, world' div element and attaches it to the map. ```typescript class HelloWorldControl: IControl { onAdd(map) { this._map = map; this._container = document.createElement('div'); this._container.className = 'maplibregl-ctrl'; this._container.textContent = 'Hello, world'; return this._container; } onRemove() { this._container.remove(); this._map = undefined; } } ``` -------------------------------- ### Create deck.gl layer using REST API Source: https://maplibre.org/maplibre-gl-js/docs/examples Create a deck.gl layer as an overlay from a REST API. This requires deck.gl to be installed and configured. ```javascript import { MapboxLayer } from '@deck.gl/mapbox'; import DeckGL from '@deck.gl/react'; const layer = new MapboxLayer({ id: 'my-deckgl-layer', type: 'custom', onAdd: (map, gl) => { const deck = new DeckGL({ gl, layers: [ new GeoJsonLayer({ id: 'geojson', data: 'YOUR_REST_API_ENDPOINT', getPointRadius: 100, pointRadiusMinPixels: 1, pointRadiusMaxPixels: 100 }) ] }); } }); map.on('load', () => { map.addLayer(layer); }); ``` -------------------------------- ### Initialize Map with Camera Options Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/CameraOptions Demonstrates how to set the initial perspective of the map using CameraOptions when creating a new Map instance. All properties are optional. ```javascript let map = new Map({ container: 'map', style: 'https://demotiles.maplibre.org/style.json', center: [-73.5804, 45.53483], pitch: 60, bearing: -60, zoom: 10 }); ``` -------------------------------- ### Import and Initialize Map Class Source: https://maplibre.org/maplibre-gl-js/docs/API Demonstrates how to import the Map class and create a new map instance. It's recommended to import only what you need. ```javascript import {Map} from 'maplibre-gl'; const map = new Map(...) ``` -------------------------------- ### Initialize a Map in an HTML Element Source: https://maplibre.org/maplibre-gl-js/docs/examples Basic map initialization in an HTML element. This example uses a style with MLT (MapLibre Tiles) encoding. ```javascript const map = new maplibregl.Map({ container: 'map', style: 'https://demotiles.maplibre.org/style.json', center: [-0.1278, 51.5074], zoom: 10 }); ``` -------------------------------- ### Display HTML clusters with custom properties Source: https://maplibre.org/maplibre-gl-js/docs/examples Extend clustering with HTML markers and custom property expressions. This example shows how to create custom cluster markers. ```javascript map.on('load', () => { map.addSource('points', { type: 'geojson', data: 'your-geojson-data-url', cluster: true, clusterMaxZoom: 14, clusterRadius: 50 }); map.addLayer({ id: 'clusters', type: 'symbol', source: 'points', filter: ['has', 'point_count'], layout: { 'icon-image': 'custom-cluster-icon', 'icon-size': [ 'step', ['get', 'point_count'], 0.5, 100, 1 ] } }); map.on('render', () => { const clusterCount = document.getElementById('cluster-count'); if (clusterCount) { clusterCount.textContent = map.querySourceFeatures('points', { filter: ['has', 'point_count'] }).length; } }); }); // You would also need to define 'custom-cluster-icon' using map.addImage() ``` -------------------------------- ### touchstart Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType Fired when a `touchstart` event occurs within the map. ```APIDOC ## touchstart ### Description Fired when a `touchstart` event occurs within the map. ### Event Type MapTouchEvent ``` -------------------------------- ### Create Production Standalone Build Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Generates the production-ready `maplibre-gl.js` and `maplibre-gl.css` files. ```bash npm run build-prod npm run build-css ``` -------------------------------- ### Create a Marker with Options Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Marker Initialize a Marker with custom options such as color and draggable state, then set its location and add it to the map. ```javascript let marker = new Marker({ color: "#FFFFFF", draggable: true }).setLngLat([30.5, 50.5]) .addTo(map); ``` -------------------------------- ### zoomstart Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType 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. ```APIDOC ## zoomstart ### Description 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. ### Event Type MapLibreEvent ``` -------------------------------- ### TransformStyleFunction Usage Example Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/TransformStyleFunction An example demonstrating how to use TransformStyleFunction with map.setStyle to modify sprite paths, glyphs, sources, and layers, including copying elements from the previous style. ```APIDOC ## Example ```javascript map.setStyle('https://demotiles.maplibre.org/style.json', { transformStyle: (previousStyle, nextStyle) => ({ ...nextStyle, // make relative sprite path like "../sprite" absolute sprite: new URL(nextStyle.sprite, "https://demotiles.maplibre.org/styles/osm-bright-gl-style/sprites/").href, // make relative glyphs path like "../fonts/{fontstack}/{range}.pbf" absolute glyphs: new URL(nextStyle.glyphs, "https://demotiles.maplibre.org/font/").href, sources: { // make relative vector url like "../../" absolute ...nextStyle.sources.map(source => { if (source.url) { source.url = new URL(source.url, "https://tiles.openfreemap.org/planet"); } return source; }), // copy a source from previous style 'osm': previousStyle.sources.osm }, layers: [ // background layer nextStyle.layers[0], // copy a layer from previous style previousStyle.layers[0], // other layers from the next style ...nextStyle.layers.slice(1).map(layer => { // hide the layers we don't need from demotiles style if (layer.id.startsWith('geolines')) { layer.layout = {...layer.layout || {}, visibility: 'none'}; // filter out US polygons } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) { layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA']; } return layer; }) ] }) }); ``` ``` -------------------------------- ### Get Layers Order Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Get an array of all layer IDs currently in the map's style, in their rendering order. This is useful for understanding layer stacking or for programmatic layer manipulation. ```javascript const orderedLayerIds = map.getLayersOrder(); ``` -------------------------------- ### getProjection() Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Gets the ProjectionSpecification. ```APIDOC ## getProjection() ### Description Gets the ProjectionSpecification. ### Method GET ### Endpoint /map/projection ### Returns #### Success Response (200) - **projection** (ProjectionSpecification) - the projection specification. ### Example ```javascript let projection = map.getProjection(); ``` ``` -------------------------------- ### Transform Request Example Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/RequestParameters Use transformRequest to modify requests that begin with `http://myHost`. This example shows how to change the URL protocol from http to https, add custom headers, and include credentials for cross-origin requests. ```javascript // use transformRequest to modify requests that begin with `http://myHost` transformRequest: function(url, resourceType) { if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) { return { url: url.replace('http', 'https'), headers: { 'my-custom-header': true }, credentials: 'include' // Include cookies for cross-origin requests } } } ``` -------------------------------- ### getTerrain() Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Get the terrain-options if terrain is loaded. ```APIDOC ## getTerrain() ### Description Get the terrain-options if terrain is loaded. ### Method GET ### Endpoint /map/terrain ### Returns #### Success Response (200) - **terrain** (TerrainSpecification) - the TerrainSpecification passed to setTerrain ### Example ```javascript map.getTerrain(); // { source: 'terrain' }; ``` ``` -------------------------------- ### getOffset() Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Marker Gets the current offset of the marker in pixels from its anchor point. ```APIDOC ## getOffset ### Description Get the marker's offset. ### Returns `Point` - The marker's screen coordinates in pixels. ### Example ```javascript let offset = marker.getOffset(); ``` ``` -------------------------------- ### Get center elevation Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieve the elevation of the map's current center point. ```javascript let centerElevation = map.getCenterElevation(); ``` -------------------------------- ### showPadding Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Gets and sets a Boolean indicating whether the map visualizes padding offsets. ```APIDOC ## showPadding ### Description Gets and sets a Boolean indicating whether the map will visualize the padding offsets. ### Accessor * **get showPadding**(): `boolean` ### Returns `boolean` ``` -------------------------------- ### movestart Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType 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. ```APIDOC ## movestart ### Description 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. ### Event Type `MapLibreEvent` ``` -------------------------------- ### Initialize Map with TerrainControl Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/TerrainControl Demonstrates how to initialize a map and add a TerrainControl to it. The control can be configured with a source for terrain data. ```javascript let map = new Map({TerrainControl: false}) .addControl(new TerrainControl({ source: "terrain" })); ``` -------------------------------- ### Geocode with Nominatim Source: https://maplibre.org/maplibre-gl-js/docs/examples Geocode with Nominatim and the maplibre-gl-geocoder plugin. Requires the maplibre-gl-geocoder plugin to be installed and configured. ```javascript import MapLibreGlGeocoder from '@maplibre/maplibre-gl-geocoder'; map.addControl(new MapLibreGlGeocoder({ accessToken: 'YOUR_MAPTILER_API_KEY', // You can also specify a different Nominatim URL if needed // geocoderService: 'https://nominatim.openstreetmap.org/search' })); ``` -------------------------------- ### getZoom Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Gets the current zoom level of the map. This value determines the scale at which the map is displayed. ```APIDOC ## getZoom() ### Description Returns the map's current zoom level. ### Method GET ### Endpoint /map/camera/zoom ### Returns `number` - The map's current zoom level. ### Example ```javascript map.getZoom(); ``` ``` -------------------------------- ### pitchstart Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType Fired whenever the map's pitch (tilt) begins a change as the result of either user interaction or methods such as Map.flyTo . ```APIDOC ## pitchstart ### Description Fired whenever the map's pitch (tilt) begins a change as the result of either user interaction or methods such as Map.flyTo . ### Event Type `MapLibreEvent` ``` -------------------------------- ### getWorkerUrl() Source: https://maplibre.org/maplibre-gl-js/docs/API/functions/getWorkerUrl Gets the worker url. This function returns the URL of the web worker used by maplibre-gl-js. ```APIDOC ## getWorkerUrl() ### Description Gets the worker url. ### Returns `string` - The worker url ``` -------------------------------- ### Implement Dynamic Flashing Square Icon Source: https://maplibre.org/maplibre-gl-js/docs/API/interfaces/StyleImageInterface Example of implementing the StyleImageInterface to create a flashing square icon. The `render` method updates the image data based on time, and `triggerRepaint` ensures the map redraws. Use this when an image needs to change dynamically on every frame. ```javascript let flashingSquare = { width: 64, height: 64, data: new Uint8Array(64 * 64 * 4), onAdd: function(map) { this.map = map; }, render: function() { // keep repainting while the icon is on the map this.map.triggerRepaint(); // alternate between black and white based on the time let value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0; // check if image needs to be changed if (value !== this.previousValue) { this.previousValue = value; let bytesPerPixel = 4; for (let x = 0; x < this.width; x++) { for (let y = 0; y < this.height; y++) { let offset = (y * this.width + x) * bytesPerPixel; this.data[offset + 0] = value; this.data[offset + 1] = value; this.data[offset + 2] = value; this.data[offset + 3] = 255; } } // return true to indicate that the image changed return true; } } } map.addImage('flashing_square', flashingSquare); ``` -------------------------------- ### Display a popup Source: https://maplibre.org/maplibre-gl-js/docs/examples Add a popup to the map. This is a basic example of creating and adding a popup at specific coordinates. ```javascript const popup = new maplibregl.Popup() .setLngLat([-0.1278, 51.5074]) .setHTML('

Hello world!

') .addTo(map); ``` -------------------------------- ### Initialize LngLatBounds with LngLat objects Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/LngLatBounds Create a LngLatBounds object using two LngLat objects representing the southwest and northeast corners. ```javascript let sw = new LngLat(-73.9876, 40.7661); let ne = new LngLat(-73.9397, 40.8002); let llb = new LngLatBounds(sw, ne); ``` -------------------------------- ### load Event Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapEventType Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred. See Draw GeoJSON points, Add live realtime data, and Animate a point. ```APIDOC ## load > **load** : `MapLibreEvent` Defined in: ui/events.ts:168 Fired immediately after all necessary resources have been downloaded and the first visually complete rendering of the map has occurred. #### See * Draw GeoJSON points * Add live realtime data * Animate a point ``` -------------------------------- ### Initialize LngLatBounds with an array of LngLatLike objects Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/LngLatBounds Create a LngLatBounds object using an array containing two LngLatLike objects: the southwest and northeast corners. ```javascript let llb = new LngLatBounds([sw, ne]); ``` -------------------------------- ### Get Layer Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieve a style layer object by its ID. This allows inspection or modification of layer properties. ```javascript let stateDataLayer = map.getLayer('state-data'); ``` -------------------------------- ### Map Initialization Options Source: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MapOptions These options are used when creating a new map instance to configure its initial state and behavior. ```APIDOC ## Map Options ### `container` - **Type**: `HTMLElement` | `string` - **Description**: The HTML element in which MapLibre GL JS will render the map, or the element's string `id`. The specified element must have no children. ### `interactive`? - **Type**: `boolean` - **Description**: If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction. - **Default**: `true` ### `hash`? - **Type**: `boolean` | `string` - **Description**: If `true`, the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL. An additional string may optionally be provided as an alternative to indicate a parameter-styled hash. - **Default**: `false` ### `dragRotate`? - **Type**: `boolean` - **Description**: If `true`, the "drag to rotate" interaction is enabled. - **Default**: `true` ### `dragPan`? - **Type**: `boolean` | `DragPanOptions` - **Description**: If `true`, the "drag to pan" interaction is enabled. An `Object` value is passed as options to `DragPanHandler.enable`. - **Default**: `true` ### `doubleClickZoom`? - **Type**: `boolean` - **Description**: If `true`, the "double click to zoom" interaction is enabled. - **Default**: `true` ### `cooperativeGestures`? - **Type**: `GestureOptions` - **Description**: If `true` or set to an options object, the map is only accessible on desktop while holding Command/Ctrl and only accessible on mobile with two fingers. Interacting with the map using normal gestures will trigger an informational screen. - **Default**: `false` ### `elevation`? - **Type**: `number` - **Description**: The elevation of the initial geographical centerpoint of the map, in meters above sea level. - **Default**: `0` ### `fadeDuration`? - **Type**: `number` - **Description**: Controls the duration of the fade-in/fade-out animation for label collisions after initial map load, in milliseconds. This setting affects all symbol layers. - **Default**: `300` ### `crossSourceCollisions`? - **Type**: `boolean` - **Description**: If `true`, symbols from multiple sources can collide with each other during collision detection. If `false`, collision detection is run separately for the symbols in each source. - **Default**: `true` ### `collectResourceTiming`? - **Type**: `boolean` - **Description**: If `true`, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers. - **Default**: `false` ### `clickTolerance`? - **Type**: `number` - **Description**: 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). - **Default**: `3` ### `fitBoundsOptions`? - **Type**: `FitBoundsOptions` - **Description**: A `FitBoundsOptions` object to use _only_ when fitting the initial `bounds` provided. ### `experimentalZoomLevelsToOverscale`? - **Type**: `number` - **Description**: **`Experimental`** Allows overzooming by splitting vector tiles after max zoom. Defines the number of zoom levels that will overscale from map's max zoom and below. - **Default**: `undefined` ``` -------------------------------- ### Get Video Element Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/VideoSource Retrieves the underlying HTMLVideoElement associated with the VideoSource. This can be useful for advanced manipulation or debugging. ```javascript let videoElement = map.getSource('some id').getVideo(); ``` -------------------------------- ### Get the center of LngLatBounds Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/LngLatBounds Calculates and returns the geographical coordinate that is equidistant from the bounding box's corners. ```javascript let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]); llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315} ``` -------------------------------- ### Import MapLibre GL JS and Initialize Map Source: https://maplibre.org/maplibre-gl-js/docs Import the MapLibre GL JS module and its CSS, then initialize a map with specific configuration. This is a common setup for web applications. ```javascript import maplibregl from 'maplibre-gl'; import 'maplibre-gl/dist/maplibre-gl.css'; const map = new maplibregl.Map({ container: 'map', // container id style: 'https://demotiles.maplibre.org/globe.json', // style URL center: [0, 0], // starting position [lng, lat] zoom: 1 // starting zoom }); ``` -------------------------------- ### repaint Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Gets and sets a Boolean indicating whether the map will continuously repaint. Useful for performance analysis. ```APIDOC ## repaint ### Description Gets and sets a Boolean indicating whether the map will continuously repaint. This information is useful for analyzing performance. ### Accessor * **get repaint**(): `boolean` ### Returns `boolean` ``` -------------------------------- ### Get Map Zoom Level Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Returns the current zoom level of the map. This method is inherited from the Camera class. ```typescript map.getZoom(); ``` -------------------------------- ### Create a Popup and Listen for Open Event Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Popup Instantiate a Popup and attach an event listener to log a message when the popup is opened. ```typescript let popup = new Popup(); // Set an event listener that will fire // any time the popup is opened popup.on('open', () => { console.log('popup was opened'); }); ``` -------------------------------- ### Get Terrain Specification Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieves the terrain specification currently applied to the map. This returns the options passed to setTerrain. ```javascript map.getTerrain(); // { source: 'terrain' }; ``` -------------------------------- ### Listen for trackuserlocationstart Event Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/GeolocateControl Initializes the GeolocateControl and adds it to the map. It then sets up an event listener for the 'trackuserlocationstart' event, which fires when the control begins tracking the user's location. ```javascript // Initialize the geolocate control. let geolocate = new GeolocateControl({ positionOptions: { enableHighAccuracy: true }, trackUserLocation: true }); // Add the control to the map. map.addControl(geolocate); // Set an event listener that fires // when a trackuserlocationstart event occurs. geolocate.on('trackuserlocationstart', () => { console.log('A trackuserlocationstart event has occurred.') }); ``` -------------------------------- ### Initialize Map: Leaflet vs. MapLibre GL JS Source: https://maplibre.org/maplibre-gl-js/docs/guides/leaflet-migration-guide Compares the initialization of a map instance in Leaflet and MapLibre GL JS. MapLibre requires specifying a style URL. ```javascript const map = L.map('map').setView([0, 0], 2); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); ``` ```javascript import 'maplibre-gl/dist/maplibre-gl.css'; import {Map} from 'maplibre-gl'; const map = new Map({ container: 'map', style: 'https://demotiles.maplibre.org/style.json', center: [0, 0], zoom: 2 }); ``` -------------------------------- ### Fit to the bounds of a LineString Source: https://maplibre.org/maplibre-gl-js/docs/examples Get the bounds of a LineString and fit the map to those bounds. This ensures the entire line is visible. ```javascript const lineString = { type: 'Feature', geometry: { type: 'LineString', coordinates: [ [-77.036514, 38.897674], [-77.008919, 38.888131], [-76.987701, 38.904913], [-77.010369, 38.917151] ] } }; const bounds = maplibregl.LngLatBounds.convert(lineString.geometry.coordinates); map.fitBounds(bounds, { padding: 20 }); ``` -------------------------------- ### Popup Constructor Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Popup Initializes a new Popup instance. Options can be provided to customize its appearance and behavior, such as offset and CSS class. ```APIDOC ## new Popup() ### Description Initializes a new Popup instance. ### Parameters #### Parameters - **options?** (`PopupOptions`) - Optional - the options for the popup ### Returns `Popup` - A new Popup instance. ``` -------------------------------- ### Get Max Bounds Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieve the maximum geographical boundaries to which the map is constrained. Returns null if no bounds are set. ```javascript let maxBounds = map.getMaxBounds(); ``` -------------------------------- ### Get map canvas element Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieve the map's HTML canvas element. This is the element where the map is rendered. ```javascript let canvas = map.getCanvas(); ``` -------------------------------- ### isActive() Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/KeyboardHandler Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. This method is part of the Handler interface. ```APIDOC ## isActive() ### Description Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture. ### Method `boolean` ### Returns `boolean` `true` if the handler is enabled and has detected the start of a zoom/rotate gesture. ### Implementation of `Handler.isActive` ``` -------------------------------- ### Initialize LngLatBounds with an array of numbers Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/LngLatBounds Create a LngLatBounds object using an array of four numbers in the order of west, south, east, north. ```javascript let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]); ``` -------------------------------- ### Constructor Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/LngLatBounds Creates a new LngLatBounds object. It can be initialized with two LngLatLike objects, an array of four numbers (west, south, east, north), or an array containing two LngLatLike objects. ```APIDOC ## Constructor ### Description Creates a new LngLatBounds object. ### Parameters - `sw?` (["number", "number", "number", "number"] | `LngLatLike` | ["LngLatLike", "LngLatLike"]): The southwest corner of the bounding box. Can be an array of 4 numbers (west, south, east, north) or an array of two LngLatLike objects [sw, ne]. - `ne?` (`LngLatLike`): The northeast corner of the bounding box. ### Returns `LngLatBounds` ### Example ```javascript let sw = new LngLat(-73.9876, 40.7661); let ne = new LngLat(-73.9397, 40.8002); let llb = new LngLatBounds(sw, ne); ``` OR ```javascript let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]); ``` OR ```javascript let llb = new LngLatBounds([sw, ne]); ``` ``` -------------------------------- ### VideoSource Methods Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/VideoSource This section details the methods available for interacting with a VideoSource instance. ```APIDOC ## getVideo() ### Description Returns the HTML `video` element. ### Method `getVideo()` ### Returns `HTMLVideoElement` - The HTML `video` element. * * * ## listens(type: string) ### Description Returns a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type. ### Method `listens(type: string): boolean` ### Parameters #### Query Parameters - **type** (string) - Required - The event type ### Returns `boolean` - `true` if there is at least one registered listener for specified event type, `false` otherwise ### Inherited from `ImageSource`.`listens` * * * ## loaded() ### Description True if the source is loaded, false otherwise. ### Method `loaded(): boolean` ### Returns `boolean` ### Inherited from `ImageSource`.`loaded` * * * ## loadTile(tile: Tile) ### Description This method does the heavy lifting of loading a tile. In most cases it will defer the work to the relevant worker source. ### Method `loadTile(tile: Tile): Promise` ### Parameters #### Path Parameters - **tile** (Tile) - Required - The tile to load ### Returns `Promise` ### Inherited from `ImageSource`.`loadTile` * * * ## off(type: string, listener: Listener) ### Description Removes a previously registered event listener. ### Method `off(type: string, listener: Listener): VideoSource` ### Parameters #### Path Parameters - **type** (string) - Required - The event type to remove listeners for. - **listener** (Listener) - Required - The listener function to remove. ### Returns `VideoSource` ### Inherited from `ImageSource`.`off` * * * ## on(type: string, listener: Listener) ### Description Adds a listener to a specified event type. ### Method `on(type: string, listener: Listener): Subscription` ### Parameters #### Path Parameters - **type** (string) - Required - The event type to add a listen for. - **listener** (Listener) - Required - The function to be called when the event is fired. The listener function is called with the data object passed to `fire`, extended with `target` and `type` properties. ### Returns `Subscription` ### Inherited from `ImageSource`.`on` * * * ## once(type: string, listener?: Listener) ### Description Adds a listener that will be called only once to a specified event type. The listener will be called first time the event fires after the listener is registered. ### Method `once(type: string, listener?: Listener): Promise | VideoSource` ### Parameters #### Path Parameters - **type** (string) - Required - The event type to listen for. - **listener?** (Listener) - Optional - The function to be called when the event is fired the first time. ### Returns `Promise | VideoSource` - `this` or a promise if a listener is not provided ### Inherited from `ImageSource`.`once` * * * ## pause() ### Description Pauses the video. ### Method `pause()` ### Returns `void` * * * ## play() ### Description Plays the video. ### Method `play()` ### Returns `void` * * * ## prepare() ### Description Sets the video's coordinates and re-renders the map. ### Method `prepare(): this` ### Returns `this` ### Overrides `ImageSource`.`prepare` * * * ## seek(seconds: number) ### Description Sets playback to a timestamp, in seconds. ### Method `seek(seconds: number): void` ### Parameters #### Path Parameters - **seconds** (number) - Required - The timestamp in seconds. ### Returns `void` * * * ## setCoordinates(coordinates: Coordinates) ### Description Sets the image's coordinates and re-renders the map. ### Method `setCoordinates(coordinates: Coordinates): this` ### Parameters #### Path Parameters - **coordinates** (Coordinates) - Required - The new coordinates for the image. ### Returns `this` ### Inherited from `ImageSource`.`setCoordinates` ``` -------------------------------- ### Get Map Projection Specification Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieves the current projection specification of the map. This is useful for understanding how map coordinates are transformed. ```javascript let projection = map.getProjection(); ``` -------------------------------- ### Get Max Zoom Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieve the maximum allowable zoom level for the map. This value dictates the furthest users can zoom in. ```javascript let maxZoom = map.getMaxZoom(); ``` -------------------------------- ### Constructor Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/GeolocateControl Initializes a new instance of the GeolocateControl class. ```APIDOC ## Constructors ### Constructor > **new GeolocateControl**(`options`: `GeolocateControlOptions`): `GeolocateControl` Defined in: ui/control/geolocate_control.ts:275 #### Parameters Parameter | Type | Description ---|---|--- `options` | `GeolocateControlOptions` | the control's options #### Returns `GeolocateControl` #### Overrides `Evented.constructor` ``` -------------------------------- ### Clone Repository Source: https://maplibre.org/maplibre-gl-js/docs/API/_media/CONTRIBUTING Clone your forked repository to your local machine. ```bash git clone git@github.com:GithubUser/maplibre-gl-js.git ``` -------------------------------- ### Get map bearing Source: https://maplibre.org/maplibre-gl-js/docs/API/classes/Map Retrieve the current bearing of the map. The bearing indicates the compass direction that is considered 'up' on the map. ```javascript let bearing = map.getBearing(); ```