### Basic MapboxVectorLayer Usage Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/MapboxVectorLayer-api.md Initialize a MapboxVectorLayer with a Mapbox style URL and access token. This example demonstrates basic setup for adding the layer to an OpenLayers map. ```javascript import { MapboxVectorLayer } from 'ol-mapbox-style'; import { Map, View } from 'ol'; const map = new Map({ target: 'map', view: new View({ center: [0, 0], zoom: 1 }), layers: [ new MapboxVectorLayer({ styleUrl: 'mapbox://styles/mapbox/bright-v9', accessToken: 'YOUR_MAPBOX_TOKEN' }) ] }); ``` -------------------------------- ### Basic Usage with Style URL Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/apply-api.md Apply a Mapbox/MapLibre style to an OpenLayers Map using a style URL. This is the most straightforward way to get started. ```javascript import { apply } from 'ol-mapbox-style'; const map = await apply( 'map', 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_KEY' ); ``` -------------------------------- ### Debug Tests in Browser for ol-mapbox-style Source: https://github.com/openlayers/ol-mapbox-style/blob/main/README.md Use this command to start a local test server for debugging. Open a browser to the indicated host and port, then click 'DEBUG' in the console output. ```bash npm run karma ``` -------------------------------- ### Proxy URLs with transformRequest Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/configuration.md Example of a transformRequest implementation to proxy resource requests through a specified URL. ```javascript // Proxy URLs function transformRequest(url, type) { return `https://proxy.example.com/?url=${encodeURIComponent(url)}`; } ``` -------------------------------- ### Setup Vector Tile Source Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Creates or configures a VectorTileSource from a Mapbox source definition. Handles MVT tiles, TileJSON, custom projections, URL normalization, and attribution. ```typescript setupVectorSource( glSource: Object, styleUrl: string, options: Options ): Promise ``` -------------------------------- ### Core Entry Points Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/API-INDEX.md These are the primary functions to start using the ol-mapbox-style library to apply Mapbox styles to OpenLayers maps. ```APIDOC ## apply() ### Description Applies an entire Mapbox style to a map or a layer group. ### Returns `Promise` - A promise that resolves with the modified Map or LayerGroup. ## MapboxVectorLayer ### Description A convenience layer class specifically designed for Mapbox styles, extending `VectorTileLayer`. ### Returns `MapboxVectorLayer` - An instance of the MapboxVectorLayer. ## applyStyle() ### Description Applies a Mapbox style to an individual layer within a map. ### Returns `Promise` - A promise that resolves when the style has been applied. ## applyBackground() ### Description Applies only the background layer from a Mapbox style. ### Returns `Promise` - A promise that resolves when the background has been applied. ``` -------------------------------- ### Add Authentication Header with transformRequest Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/configuration.md Example of a transformRequest implementation to add an Authorization header for specific resource types. ```javascript // Add authentication header function transformRequest(url, type) { if (type === 'Source' || type === 'Tiles') { return new Request(url, { headers: { 'Authorization': 'Bearer TOKEN' } }); } } ``` -------------------------------- ### Get Style Configuration Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Use `styleConfig` to get the configuration object for a specific layer or source, which can be useful for inspection or modification. ```javascript import {styleConfig} from "ol-mapbox-style"; const config = styleConfig(map, "layer-id-1"); console.log(config); ``` -------------------------------- ### Cache Responses with transformRequest Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/configuration.md Example of a transformRequest implementation that caches responses to improve performance. ```javascript // Cache responses const cache = new Map(); function transformRequest(url, type) { if (cache.has(url)) { return cache.get(url); } // Return undefined to use default fetch } ``` -------------------------------- ### Get Source Information Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Retrieve details about a specific source on the map using `getSource`. This is useful for inspecting source properties. ```javascript import {getSource} from "ol-mapbox-style"; const source = getSource(map, "source-id-1"); ``` -------------------------------- ### Using MapLibre Style with MapboxVectorLayer Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/MapboxVectorLayer-api.md Configure a MapboxVectorLayer to use a MapLibre style URL. This example shows how to integrate external MapLibre styles by providing the style URL and an API key. ```javascript import { MapboxVectorLayer } from 'ol-mapbox-style'; const layer = new MapboxVectorLayer({ styleUrl: 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_KEY' }); map.addLayer(layer); ``` -------------------------------- ### Setup OpenLayers Layer from Mapbox Definition Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Creates an appropriate OpenLayers layer type based on a Mapbox layer definition, supporting various layer types like background, fill, line, circle, symbol, raster, and hillshade. ```typescript setupLayer( glStyle: Object, styleUrl: string, glLayer: Object, options: Options ): Layer ``` -------------------------------- ### Catching Missing Source Type Error for VectorTileLayer Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/errors.md This example demonstrates how to catch errors when a VectorTileLayer is used without a corresponding 'vector' type source in the style. It checks for the 'No vector source found' message. ```javascript import { applyStyle } from 'ol-mapbox-style'; import VectorTileLayer from 'ol/layer/VectorTile.js'; const layer = new VectorTileLayer(); try { await applyStyle(layer, styleUrl); } catch (error) { if (error.message.includes('No vector source found')) { console.error('Style has no vector tiles source'); } } ``` -------------------------------- ### Build ol-mapbox-style Library Source: https://github.com/openlayers/ol-mapbox-style/blob/main/README.md Run this command in the project's root directory to build the library. The distribution files will be located in the `dist/` folder. ```bash npm run build ``` -------------------------------- ### setupLayer Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Advanced utility to create an OpenLayers layer from a Mapbox layer definition. ```APIDOC ## setupLayer() ### Description Create OpenLayers layer from Mapbox layer definition. ### Signature ```typescript setupLayer( glStyle: Object, styleUrl: string, glLayer: Object, options: Options ): Layer ``` ### Creates appropriate layer type based on glLayer: - `'background'` - Solid color layer - `'fill'`, `'line'`, `'circle'`, `'symbol'` - Vector layers - `'raster'` - Raster tile layer - `'hillshade'` - Hillshade raster layer ``` -------------------------------- ### Run Local Tests for ol-mapbox-style Source: https://github.com/openlayers/ol-mapbox-style/blob/main/README.md Execute this command to run the project's test suite locally. Ensure you are in the project's root directory. ```bash npm test ``` -------------------------------- ### getStyleId Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Get or assign an internal ID for a style object. This is useful for caching purposes. ```APIDOC ## getStyleId() ### Description Get or assign internal ID for a style object. ### Signature ```typescript getStyleId(glStyle: Object): number ``` ### Returns Consistent ID for caching purposes. ``` -------------------------------- ### Configuration Options Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Reference for all available configuration options used when applying styles and creating layers. ```APIDOC ## Configuration Options Reference for all available configuration options used when applying styles and creating layers. ### apply() options - **accessToken** (string): Mapbox access token. - **transformRequest** (function): Callback to transform requests. - **projection** (ol.proj.Projection): The projection to use for the map. - **resolutions** (Array): Array of resolutions for the map. ### applyStyle() options - **source** (string | object): The source to use for the style. - **layers** (Array): An array of layer configurations. - **updateSource** (boolean): Whether to update the source. ### MapboxVectorLayer() options This constructor accepts over 25 options, including those from `Options` and `VectorTileLayerOptions`. ### transformRequest callback specification Provides a callback function to modify outgoing requests, allowing for custom headers or URL manipulation. ### webfonts template placeholders Details on placeholders available for web font URLs within the style configuration. ### getImage callback specification Defines the signature and behavior for a callback function used to retrieve images for the style. ### Style metadata for ol:webfonts Information on how OpenLayers specific webfont metadata is handled within Mapbox styles. ### Examples of each Practical examples demonstrating the usage of various configuration options. ``` -------------------------------- ### Get All Layers Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Use `getLayers` to retrieve all layers currently managed by the Mapbox style on the OpenLayers map. ```javascript import {getLayers} from "ol-mapbox-style"; const layers = getLayers(map); console.log(layers); ``` -------------------------------- ### setupVectorSource Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Advanced utility to create or configure a VectorTileSource from a Mapbox source definition. ```APIDOC ## setupVectorSource() ### Description Create or configure a VectorTileSource from Mapbox source definition. ### Signature ```typescript setupVectorSource( glSource: Object, styleUrl: string, options: Options ): Promise ``` ### Parameters - `glSource` - Mapbox vector source definition - `styleUrl` - Base URL for relative tile URLs - `options` - Includes accessToken, projection, resolutions ### Handles - Vector Tiles (MVT) with TileJSON - TileGrid configuration for non-standard projections - URL normalization (mapbox://) - Attribution setup ``` -------------------------------- ### Get Style ID Utility Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Retrieves a consistent internal ID for a given style object, useful for caching. ```typescript getStyleId(glStyle: Object): number ``` -------------------------------- ### Project File Structure Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/COMPLETION-REPORT.md Overview of the project's directory and file organization, indicating the purpose of each file. ```text /workspace/home/output/ ├── README.md (Start here) ├── API-INDEX.md (Navigation guide) ├── DOCUMENTATION-SUMMARY.txt (This summary) ├── COMPLETION-REPORT.md (This report) │ ├── apply-api.md (Main APIs) ├── applyStyle-api.md ├── applyBackground-api.md ├── MapboxVectorLayer-api.md │ ├── layer-management-api.md (Feature APIs) ├── feature-state-api.md │ ├── stylefunction-api.md (Advanced APIs) ├── utility-functions-api.md ├── mapbox-utilities-api.md ├── internal-utilities-api.md │ ├── configuration.md (Reference) ├── types.md └── errors.md ``` -------------------------------- ### Record Layer Information with ol-mapbox-style Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md Enable recording of style layer information for later inspection. Ensure 'apply' is called after enabling recording. ```javascript import { recordStyleLayer, styleFunctionArgs } from 'ol-mapbox-style'; recordStyleLayer(true); apply('map', styleUrl); // Later, inspect recorded info console.log(styleFunctionArgs); ``` -------------------------------- ### Get Style for Layer Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Retrieve the effective Mapbox style object for a given OpenLayers layer using `getStyleForLayer`. ```javascript import {getStyleForLayer} from "ol-mapbox-style"; const style = getStyleForLayer(layer); console.log(style); ``` -------------------------------- ### Get Feature State Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/feature-state-api.md Retrieve the current state object for a specific feature. Returns undefined if no state is set. ```js import { apply, getFeatureState } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); const state = getFeatureState(map, { source: 'buildings', id: 123 }); if (state && state.selected) { console.log('Feature is selected'); } ``` -------------------------------- ### Options Object Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md Complete options available for all style application functions. ```APIDOC ## Options Object Complete options available for all style application functions: ```typescript interface Options { accessToken?: string; // Mapbox access token transformRequest?: function; // Intercept resource requests projection?: string; // Map projection (EPSG code) resolutions?: number[]; // Custom zoom-to-resolution mapping styleUrl?: string; // Base URL for relative URLs webfonts?: string; // Web font template URL getImage?: function; // Custom image provider } ``` See [[configuration.md|configuration.md]] for complete options. ``` -------------------------------- ### Modify URLs Based on Type with transformRequest Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/configuration.md Example of a transformRequest implementation that modifies resource URLs based on their type. ```javascript // Modify URLs based on type function transformRequest(url, type) { if (type === 'Tiles') { // Use specific tile server return url.replace('api.mapbox.com', 'tiles.example.com'); } } ``` -------------------------------- ### Utility Functions Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt A collection of utility functions for retrieving style information, managing rendering, and accessing global configuration settings. ```APIDOC ## Utility Functions ### Description Provides various utility functions for working with Mapbox styles in OpenLayers, including retrieving style properties, managing rendering behavior, and accessing global configuration. ### Functions - **getValue(glLayer, property, resolution, ...): any**: Retrieves a specific property value from a Mapbox layer, considering the current resolution. - **getStyleForLayer(feature, resolution, olLayer, layerId): Style|Style[]**: Generates the OpenLayers `Style` or an array of `Style` objects for a given feature, resolution, and layer. - **recordStyleLayer(record?): void**: Records or clears style layer information, potentially for debugging or analysis. - **renderTransparent(enabled): void**: Enables or disables transparent rendering. `enabled` should be a boolean. ### Global Configuration - **styleConfig: Object**: A global configuration object for the library. Its properties are not detailed here. - **styleFunctionArgs: Object**: An object used for debugging style function arguments. Its structure is not detailed here. ``` -------------------------------- ### Publish to npm Source: https://github.com/openlayers/ol-mapbox-style/blob/main/PUBLISHING.md Publish the package to the npm registry. Ensure you are logged into npm before running this command. ```bash npm publish ``` -------------------------------- ### Get Layer Information Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Retrieve details about a specific layer on the map using `getLayer`. This is useful for inspecting layer properties. ```javascript import {getLayer} from "ol-mapbox-style"; const layer = getLayer(map, "layer-id-1"); ``` -------------------------------- ### Create MapboxVectorLayer Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/API-INDEX.md Instantiate a MapboxVectorLayer for recommended integration. Provide the style URL and your access token. ```javascript new MapboxVectorLayer({ styleUrl: 'mapbox://styles/mapbox/bright-v9', accessToken: 'YOUR_TOKEN' }) ``` -------------------------------- ### Get Style Value Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt The `getValue` function retrieves the computed value of a style property for a given feature, resolution, and map state. ```javascript import {getValue} from "ol-mapbox-style"; const color = getValue(feature, "line-color", resolution, mapState); console.log(color); ``` -------------------------------- ### Options Interface Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/types.md Main configuration object for applying styles. Includes options for access tokens, request transformations, projections, and image providers. ```typescript interface Options { accessToken?: string; transformRequest?: (url: string, resourceType: ResourceType) => Request | string | Response | Promise | void; projection?: string; resolutions?: number[]; styleUrl?: string; webfonts?: string; getImage?: (name: string, layer?: VectorLayer | VectorTileLayer) => HTMLImageElement | HTMLCanvasElement | string | undefined; accessTokenParam?: string; } ``` -------------------------------- ### Get Feature State Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Retrieve the state of a feature using `getFeatureState`. This is useful for querying the current dynamic styling properties of a feature. ```javascript import {getFeatureState} from "ol-mapbox-style"; const state = getFeatureState(map, "your-source-id", "feature-id-1"); console.log(state); // { "hover": true, "selected": false } ``` -------------------------------- ### Add and Update Mapbox Layers Dynamically Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md Demonstrates how to add a new fill layer and update an existing layer's opacity after the map has been initialized with a Mapbox style. Uses `addMapboxLayer` and `updateMapboxLayer`. ```javascript import { apply, addMapboxLayer, updateMapboxLayer } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); // Add new layer await addMapboxLayer(map, { id: 'new-layer', type: 'fill', source: 'source-id', paint: { 'fill-color': '#ff0000' } }); // Update existing layer const layer = map.get('mapbox-style').layers[0]; layer.paint['fill-opacity'] = 0.5; await updateMapboxLayer(map, layer); ``` -------------------------------- ### Get Mapbox Layer Information Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt Functions like `getMapboxLayer` and `getMapboxSource` help retrieve information about Mapbox layers and sources managed by the library. ```javascript import {getMapboxLayer, getMapboxSource} from "ol-mapbox-style"; const layer = getMapboxLayer(map, "layer-id-1"); const source = getMapboxSource(map, "source-id-1"); ``` -------------------------------- ### Create Release Branch Source: https://github.com/openlayers/ol-mapbox-style/blob/main/PUBLISHING.md Create a new branch for release-specific changes. Replace '2.11.0' with the target release version. ```bash git checkout -b release-v2.11.0 origin/main ``` -------------------------------- ### getStyleForLayer() Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/utility-functions-api.md Get the OpenLayers style for a specific feature in a layer. This function is useful for rendering individual features with styles derived from a Mapbox style configuration. ```APIDOC ## getStyleForLayer() ### Description Get the OpenLayers style for a specific feature in a layer. ### Signature ```typescript getStyleForLayer( feature: Feature, resolution: number, olLayer: VectorLayer | VectorTileLayer, layerId: string ): Style | Style[] ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **feature** (Feature) - Required - Feature to style - **resolution** (number) - Required - Current map resolution - **olLayer** (`VectorLayer | VectorTileLayer`) - Required - OpenLayers layer - **layerId** (string) - Required - Mapbox layer ID ### Response #### Success Response (200) - **style** (`Style | Style[]`) - OpenLayers Style or array of Styles for rendering the feature. ### Request Example ```js import { getStyleForLayer } from 'ol-mapbox-style'; const style = getStyleForLayer(feature, resolution, layer, 'roads'); ``` ### Response Example ```json { "style": { "type": "Polygon" } } ``` ``` -------------------------------- ### Get Resolution for Zoom - JavaScript Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Converts a zoom level to its corresponding map resolution. The zoom level can be fractional. Requires an array of resolutions from a tile grid. ```javascript import { getResolutionForZoom } from 'ol-mapbox-style/src/util.js'; const resolutions = [78271.51696402048, 39135.75848201024, ...]; const resolution = getResolutionForZoom(10, resolutions); // ~76.4 ``` -------------------------------- ### Get Mapbox Layer Definition Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/layer-management-api.md Retrieve the Mapbox/MapLibre style layer definition for a specific layer ID. Use this to inspect paint properties or other layer configurations. ```javascript import { apply, getMapboxLayer } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); const layer = getMapboxLayer(map, 'roads'); console.log(layer.paint); // Paint properties ``` -------------------------------- ### Get Filter Cache - TypeScript Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Retrieves the filter expression cache for a given style. This cache stores compiled filter expressions and is used internally by stylefunction and updateMapboxLayer. ```typescript getFilterCache(glStyle: Object): Object ``` -------------------------------- ### Handle Errors During Style Application Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md Implement error handling for the 'apply' function to catch and log potential issues during style application. Check for specific error messages to handle different failure scenarios. ```javascript import { apply } from 'ol-mapbox-style'; try { const map = await apply('map', styleUrl); } catch (error) { console.error('Style application failed:', error.message); if (error.message.includes('version 8')) { // Handle version error } } ``` -------------------------------- ### Create and Push Git Tag Source: https://github.com/openlayers/ol-mapbox-style/blob/main/PUBLISHING.md Create an annotated Git tag for the release and push it to the remote repository. This tag marks the specific version on GitHub. ```bash git tag -a v2.11.0 -m "2.11.0" git push --tags origin ``` -------------------------------- ### Multi-layer Selection Across Same Source Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/feature-state-api.md Demonstrates that feature state is shared across all layers using the same source. Setting state on one layer affects all others using the same source. ```js import { apply, setFeatureState } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); // Feature state is shared across all layers using the same source function selectBuilding(buildingId) { setFeatureState(map, { source: 'buildings', id: buildingId }, { selected: true }); // This state applies to 'building-fill', 'building-outline', // and any other layers using the 'buildings' source } ``` -------------------------------- ### Get Zoom for Resolution - JavaScript Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Converts a map resolution to its corresponding zoom level. The zoom level can be fractional, which is useful for zoom animations. Requires an array of resolutions from a tile grid. ```javascript import { getZoomForResolution } from 'ol-mapbox-style/src/util.js'; const resolutions = [78271.51696402048, 39135.75848201024, ...]; const zoom = getZoomForResolution(1000, resolutions); // ~9.5 ``` -------------------------------- ### getValue() Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/utility-functions-api.md Get the styled value for a property at a given resolution. Evaluates Mapbox layer style properties considering zoom transitions and feature-dependent expressions. Used internally by the style function. ```APIDOC ## getValue() ### Description Get the styled value for a property at a given resolution. ### Signature ```typescript getValue( glLayer: Object, property: string, resolution: number, feature?: Feature, state?: Object, functionCache?: Object ): any ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **glLayer** (Object) - Required - Mapbox layer definition - **property** (string) - Required - Paint or layout property name - **resolution** (number) - Required - Current map resolution - **feature** (Feature) - Optional - Feature for property evaluation - **state** (Object) - Optional - Optional feature state - **functionCache** (Object) - Optional - Optional function cache for performance ### Response #### Success Response (200) - **value** (any) - The computed value for the property at the given resolution and feature. ### Request Example ```js import { getValue } from 'ol-mapbox-style'; const layer = style.layers.find(l => l.id === 'roads'); const color = getValue(layer, 'line-color', 1000); // Get color at zoom 9 ``` ### Response Example ```json { "value": "#0000FF" } ``` ``` -------------------------------- ### Apply Style and Source to a VectorTile Layer Source: https://github.com/openlayers/ol-mapbox-style/blob/main/README.md Use `applyStyle` to assign a Mapbox/MapLibre style and source to an existing VectorTile layer. Supports 'mapbox://' URLs. ```javascript import {applyStyle} from 'ol-mapbox-style'; import VectorTileLayer from 'ol/layer/VectorTile.js' const layer = new VectorTileLayer({declutter: true}); applyStyle(layer, 'mapbox://styles/mapbox/bright-v9', {accessToken: 'YOUR_MAPBOX_TOKEN'}); ``` -------------------------------- ### 'error' Event Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/MapboxVectorLayer-api.md Listen for 'error' events emitted when the style fails to load or configure. ```APIDOC ## layer.on('error', callback) ### Description Emitted when the style fails to load or configure. ### Parameters #### Event - **error** (Error) - The error object describing what failed. ``` -------------------------------- ### Get OpenLayers Layer Instance Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/layer-management-api.md Find the OpenLayers layer instance that renders a given Mapbox style layer ID. This is useful for directly manipulating the OpenLayers layer, such as setting its opacity. ```javascript import { apply, getLayer } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); const olLayer = getLayer(map, 'roads'); olLayer.setOpacity(0.5); ``` -------------------------------- ### MapboxVectorLayer Constructor Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/MapboxVectorLayer-api.md Instantiate a MapboxVectorLayer with various configuration options for loading and displaying Mapbox/MapLibre styles. ```APIDOC ## new MapboxVectorLayer(options) ### Description Creates a new MapboxVectorLayer instance. ### Parameters #### Options - **styleUrl** (string) - Required - The URL to the Mapbox/MapLibre style JSON. - **accessToken** (string) - Optional - The Mapbox access token. - **source** (string) - Optional - Specifies which vector source to render if the style has multiple. - **layers** (Array) - Optional - An array of layer IDs to render from the style. - **renderMode** (string) - Optional - The rendering mode for the layer (e.g., 'vector'). - **renderBuffer** (number) - Optional - The buffer size for rendering. - **declutter** (boolean) - Optional - Whether to enable decluttering. - **minZoom** (number) - Optional - The minimum zoom level for the layer. - **maxZoom** (number) - Optional - The maximum zoom level for the layer. - **background** (string) - Optional - Overrides the background color of the style. ``` -------------------------------- ### MapboxVectorLayer Error Handling Example Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/MapboxVectorLayer-api.md Implement error handling for a MapboxVectorLayer by attaching an event listener to the 'error' event. This allows you to log or react to errors that occur during style loading or processing. ```javascript import { MapboxVectorLayer } from 'ol-mapbox-style'; const layer = new MapboxVectorLayer({ styleUrl: 'mapbox://styles/mapbox/bright-v9', accessToken: 'YOUR_TOKEN' }); layer.on('error', (event) => { console.error('Failed to load style:', event.error.message); }); map.addLayer(layer); ``` -------------------------------- ### Internal Utilities Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/DOCUMENTATION-SUMMARY.txt A collection of internal utility functions for cache management, zoom/resolution calculations, resource loading, font handling, and canvas drawing. ```APIDOC ## Internal Utilities ### Description This section details various internal utility functions used within the ol-mapbox-style library. These utilities cover aspects like caching, resource loading, text manipulation, and canvas drawing, primarily for internal use but potentially useful for advanced debugging or customization. ### Cache Management - **getFunctionCache(glStyle): Object**: Retrieves the function cache associated with a given Mapbox style. - **getFilterCache(glStyle): Object**: Retrieves the filter cache associated with a given Mapbox style. - **clearFunctionCache(): void**: Clears the global function cache. - **getStyleId(glStyle): number**: Generates a unique ID for a Mapbox style object. ### Zoom/Resolution - **getZoomForResolution(resolution, resolutions): number**: Calculates the zoom level corresponding to a given map resolution. - **getResolutionForZoom(zoom, resolutions): number**: Calculates the map resolution corresponding to a given zoom level. ### Resource Loading - **fetchResource(resourceType, url, options, metadata): Promise**: A generic function to fetch resources of a specified type from a URL. - **getGlStyle(glStyleOrUrl, options): Promise**: Fetches and parses a Mapbox GL style object from a URL or directly from an object. - **getTileJson(glSource, styleUrl, options): Promise**: Fetches and parses TileJSON data for a given Mapbox GL source. ### Text/Fonts - **applyLetterSpacing(text, letterSpacing): string**: Applies letter spacing to a given text string. - **wrapText(text, font, em, letterSpacing): string**: Wraps text to fit within specified dimensions, considering font properties. - **getFonts(fonts, templateUrl): string[]**: Retrieves font URLs from a Mapbox style definition. ### Canvas/Drawing - **createCanvas(width, height): Canvas|OffscreenCanvas**: Creates a new canvas element with the specified dimensions. - **drawIconHalo(image, color, width): HTMLCanvasElement**: Draws a halo effect around an icon image on a canvas. - **drawSDF(image, area, color): HTMLCanvasElement**: Draws a Signed Distance Field (SDF) glyph on a canvas with a specified color. ``` -------------------------------- ### Catching Invalid Source Type Error Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/errors.md This example shows how to catch errors when a referenced source is not of type 'vector' or 'geojson', which are the only types supported by stylefunction. It checks for the 'not of type' error message. ```javascript try { const styleFunc = stylefunction(layer, style, 'raster-source'); } catch (error) { if (error.message.includes('not of type')) { console.error('Cannot render raster sources with stylefunction'); } } ``` -------------------------------- ### General Options Object Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md Defines the complete set of options available for all style application functions. Use these to customize how styles are loaded and applied. ```typescript interface Options { accessToken?: string; // Mapbox access token transformRequest?: function; // Intercept resource requests projection?: string; // Map projection (EPSG code) resolutions?: number[]; // Custom zoom-to-resolution mapping styleUrl?: string; // Base URL for relative URLs webfonts?: string; // Web font template URL getImage?: function; // Custom image provider } ``` -------------------------------- ### Finalize Layer with Style and Source Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Applies style and source to an OpenLayers layer after its creation. Handles source loading, style function application, zoom level visibility, and layer property setup. ```typescript finalizeLayer( layer: Layer, layerIds: string[], glStyle: Object, styleUrl: string, mapOrGroup: Map | LayerGroup, options?: Options ): Promise ``` -------------------------------- ### Import Internal OpenLayers Mapbox Style Utilities Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/API-INDEX.md Import lower-level utility functions for advanced use cases, including style function helpers, caching, and resource fetching. ```javascript // Lower-level utilities import { getValue, styleFunctionArgs, getStyleId, getStyleFunctionKey, getFunctionCache, clearFunctionCache, getFilterCache, deg2rad, defaultResolutions, emptyObj, getZoomForResolution, getResolutionForZoom, fetchResource, getGlStyle, getTileJson, createCanvas, drawIconHalo, drawSDF, applyLetterSpacing, wrapText, getFonts } from 'ol-mapbox-style/src/...'; ``` -------------------------------- ### ApplyStyleOptions Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/types.md Additional options specific to the `applyStyle()` function. ```APIDOC ## ApplyStyleOptions Additional options specific to `applyStyle()` function. ### Interface ```typescript interface ApplyStyleOptions { source?: string; layers?: string[]; updateSource?: boolean; } ``` ### Properties | Key | Type | Default | Description | |---|---|---|---| | `source` | string | `''` | Source ID from style to apply. Empty string uses first matching source | | `layers` | `string[]` | undefined | Specific style layer IDs to apply. Must share same source | | `updateSource` | boolean | true | Whether to create/update the OpenLayers source from style definition | ``` -------------------------------- ### Get Function Cache - TypeScript Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Retrieves the compiled expression cache for a given style. This cache stores compiled Mapbox filter and expression functions to improve performance. It is used internally by stylefunction and updateMapboxLayer. ```typescript getFunctionCache(glStyle: Object): Object ``` -------------------------------- ### apply() Function Signature Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/apply-api.md The apply function takes a map target, a style definition, and optional configuration options, returning a Promise that resolves to the applied Map or LayerGroup. ```APIDOC ## apply(mapOrGroupOrElement, style, options) ### Description Applies a Mapbox/MapLibre style to an OpenLayers Map or LayerGroup, creating layers and sources from the style definition. ### Parameters #### mapOrGroupOrElement - **Type**: `string | HTMLElement | Map | LayerGroup` - **Required**: Yes - **Description**: Map target element ID (string), HTML element, OpenLayers Map, or LayerGroup instance #### style - **Type**: `string | Object` - **Required**: Yes - **Description**: Mapbox/MapLibre style object or URL (supports `mapbox://`, `https://`, and data URLs) #### options - **Type**: `Options` - **Required**: No - **Default**: `{}` - **Description**: Configuration options for style application ### Options Object #### accessToken - **Type**: `string` - **Default**: `undefined` - **Description**: Access token for Mapbox URLs (`mapbox://` style) #### transformRequest - **Type**: `function` - **Default**: `undefined` - **Description**: Function to intercept and modify resource requests. Called with `(url, resourceType)` #### projection - **Type**: `string` - **Default**: `'EPSG:3857'` - **Description**: EPSG code for the projection. All sources must be in this projection #### resolutions - **Type**: `Array` - **Default**: `undefined` - **Description**: Custom resolutions for zoom-to-resolution mapping #### styleUrl - **Type**: `string` - **Default**: `undefined` - **Description**: Base URL of the style (required for relative sprite/source URLs) #### webfonts - **Type**: `string` - **Default**: `Fontsource CDN` - **Description**: Template URL for web font resolution #### getImage - **Type**: `function` - **Default**: `undefined` - **Description**: Custom image provider function for icons #### accessTokenParam - **Type**: `string` - **Default**: `'access_token'` - **Description**: Parameter name for access token in URLs ### Return Value A Promise that resolves to the applied Map or LayerGroup instance when the style is fully applied and all resources (sprites, fonts, tiles) are loaded. ### Throws - Rejects with error if style version is not 8 - Rejects if style URL cannot be loaded - Rejects if required resources (sprites, tiles) fail to load ``` -------------------------------- ### Get Styled Value for a Property Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/utility-functions-api.md Use this function to retrieve the computed value of a Mapbox layer property at a given resolution. It considers zoom transitions and feature-dependent expressions. Ensure the `ol-mapbox-style` library is imported. ```javascript import { getValue } from 'ol-mapbox-style'; const layer = style.layers.find(l => l.id === 'roads'); const color = getValue(layer, 'line-color', 1000); // Get color at zoom 9 ``` -------------------------------- ### Get All Layers for a Mapbox Source Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/layer-management-api.md Retrieves all OpenLayers layer instances associated with a specific Mapbox source ID from a given map or layer group. Useful for modifying properties of all layers using a particular source. ```javascript import { apply, getLayers } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); const layers = getLayers(map, 'mapbox-tiles'); layers.forEach(layer => { layer.setOpacity(0.7); }); ``` -------------------------------- ### Get OpenLayers Source by Mapbox Source ID Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/layer-management-api.md Fetches the OpenLayers source instance corresponding to a given Mapbox source ID. Returns undefined if the source is not found. Useful for inspecting or manipulating the data source of a layer. ```javascript import { apply, getSource } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); const source = getSource(map, 'buildings'); console.log(source.getAttributions()); ``` -------------------------------- ### Apply Background to Map with URL Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/applyBackground-api.md Applies the background from a Mapbox/MapLibre style URL to an OpenLayers map. Ensure the map and view are initialized before calling. ```javascript import { applyBackground } from 'ol-mapbox-style'; import { Map } from 'ol'; const map = new Map({ target: 'map', view: new View({center: [0, 0], zoom: 1}) }); await applyBackground( map, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_KEY' ); ``` -------------------------------- ### fetchResource Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Low-level function to fetch style resources with caching and request transformation. Handles request deduplication, response transformation, and error handling. ```APIDOC ## fetchResource() ### Description Low-level function to fetch style resources with caching and request transformation. ### Parameters - `resourceType` (ResourceType) - Type: 'Style', 'Source', 'Sprite', 'SpriteImage', 'Tiles', 'GeoJSON' - `url` (string) - Resource URL - `options` (Options) - Options including transformRequest - `metadata` (Object) - Optional object to fill with request metadata ### Returns Promise ### Handles - Request deduplication (multiple requests to same URL return same promise) - Response transformation via transformRequest - Error handling with meaningful messages ``` -------------------------------- ### Get OpenLayers Style for a Feature Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/utility-functions-api.md This function generates the appropriate OpenLayers `Style` object(s) for a given feature within a specific Mapbox layer. It requires the feature, current resolution, the OpenLayers layer, and the Mapbox layer ID. Ensure the `ol-mapbox-style` library is imported. ```javascript import { getStyleForLayer } from 'ol-mapbox-style'; const style = getStyleForLayer(feature, resolution, layer, 'roads'); ``` -------------------------------- ### MapboxVectorLayer Options Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md Options accepted by the MapboxVectorLayer constructor. ```APIDOC ## MapboxVectorLayer Options The [[MapboxVectorLayer|MapboxVectorLayer]] constructor accepts: ```typescript interface MapboxVectorLayerOptions extends Options { styleUrl: string; // Required: Mapbox/MapLibre style URL source?: string; // Source ID if style has multiple sources layers?: string[]; // Specific layer IDs to render declutter?: boolean; // Icon/text decluttering (default: true) background?: Color | false; // Background color // ... plus all VectorTileLayer options } ``` See [[MapboxVectorLayer-api.md|MapboxVectorLayer]] for full details. ``` -------------------------------- ### Fetch Resource with Caching and Transformation Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Low-level function to fetch style resources. Handles request deduplication, response transformation, and error handling. Used internally for style and sprite loading. ```typescript fetchResource( resourceType: ResourceType, url: string, options?: Options, metadata?: Object ): Promise ``` -------------------------------- ### Interactive Feature Highlighting Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/feature-state-api.md Set feature state on mouse over to highlight features. Ensure to clear state on mouse out. ```js import { apply, setFeatureState, getFeatureState } from 'ol-mapbox-style'; const map = await apply('map', styleUrl); // On mouse over map.on('pointermove', (event) => { const features = map.getFeaturesAtPixel(event.pixel); if (features.length > 0) { const feature = features[0]; const sourceId = feature.getProperties()['source']; setFeatureState(map, { source: sourceId, id: feature.getId() }, { hover: true }); } }); // On mouse out map.on('pointerout', (event) => { const features = map.getFeaturesAtPixel(event.pixel); if (features.length > 0) { const feature = features[0]; setFeatureState(map, { source: 'buildings', id: feature.getId() }, null); } }); ``` -------------------------------- ### Basic Style Function Creation Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/stylefunction-api.md Applies a Mapbox style to an OpenLayers Vector layer. Fetch the style JSON and then create and set the style function. ```javascript import { stylefunction } from 'ol-mapbox-style'; import VectorLayer from 'ol/layer/Vector.js'; import VectorSource from 'ol/source/Vector.js'; import GeoJSON from 'ol/format/GeoJSON.js'; const layer = new VectorLayer({ source: new VectorSource({ format: new GeoJSON(), url: 'data.geojson' }) }); fetch('style.json') .then(r => r.json()) .then(style => { const styleFunc = stylefunction(layer, style, 'mydata'); layer.setStyle(styleFunc); }); ``` -------------------------------- ### Style Function with Custom Image Provider Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/stylefunction-api.md Provides a custom image provider function to the style function. This allows for dynamic loading or custom handling of images used in the style. ```javascript import { stylefunction } from 'ol-mapbox-style'; const customImages = { 'my-icon': new Image() }; const styleFunc = stylefunction( layer, style, 'source-id', undefined, undefined, undefined, undefined, (name) => { if (name in customImages) { return customImages[name]; } return undefined; // Use default sprite } ); ``` -------------------------------- ### Key Type Definitions Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/README.md A list of key type definitions available for use with the Mapbox style APIs. ```APIDOC ## Type Definitions Complete type reference for all APIs: - [[types.md|types.md]] - All TypeScript types and interfaces Key types: - `FeatureIdentifier` - Feature ID and source - `Options` - Configuration options - `ApplyStyleOptions` - Additional applyStyle options - `MapboxVectorLayerOptions` - Layer constructor options - `ResourceType` - Resource type enum - `Sprite` - Sprite definition ``` -------------------------------- ### Style Function with Pre-loaded Sprite Data Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/stylefunction-api.md Integrates pre-loaded sprite data and URL with the style function. This is useful when sprites are not automatically discoverable or need to be managed manually. ```javascript import { stylefunction } from 'ol-mapbox-style'; const spriteData = { 'icon-name': {x: 0, y: 0, width: 32, height: 32}, 'another-icon': {x: 32, y: 0, width: 32, height: 32} }; const spriteImageUrl = 'https://example.com/sprites.png'; const styleFunc = stylefunction( layer, style, 'source-id', undefined, spriteData, spriteImageUrl ); ``` -------------------------------- ### Apply all layers from a source Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/applyStyle-api.md Applies all layers from a Mapbox/MapLibre style to a VectorTileLayer. Ensure the layer is added to the map after applying the style. ```javascript import { applyStyle } from 'ol-mapbox-style'; import VectorTileLayer from 'ol/layer/VectorTile.js'; const layer = new VectorTileLayer(); await applyStyle( layer, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_KEY' ); map.addLayer(layer); ``` -------------------------------- ### Commit Version and Changelog Changes Source: https://github.com/openlayers/ol-mapbox-style/blob/main/PUBLISHING.md Stage and commit changes to package.json, package-lock.json, and CHANGELOG.md. This includes bumping the version number and updating the changelog. ```bash git add package.json package-lock.json CHANGELOG.md git commit -m "Changes for 2.11.0" ``` -------------------------------- ### getGlStyle Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/internal-utilities-api.md Load and parse a Mapbox style from URL or object. Handles URL fetching, caching, JSON parsing, and URL normalization. ```APIDOC ## getGlStyle() ### Description Load and parse a Mapbox style from URL or object. ### Parameters - `glStyleOrUrl` (string | Object) - Style URL (http/https/data), JSON string, or object - `options` (Options) - Options including accessToken, transformRequest ### Returns Promise - Parsed style object ### Handles - URL fetching and caching - JSON string parsing - mapbox:// URL normalization - data: URL resolution ``` -------------------------------- ### Set Global Style Configuration Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/utility-functions-api.md Set global configuration values that can be accessed within style expressions using the `config()` function. This is useful for dynamic styling based on external factors like user preferences. ```javascript import { styleConfig, apply } from 'ol-mapbox-style'; // Set config values styleConfig['user-preference'] = 'dark'; const map = await apply('map', styleUrl); ``` ```json { "paint": { "fill-color": [ "case", ["==", ["config", "user-preference"], "dark"], "#1a1a1a", "#ffffff" ] } } ``` -------------------------------- ### Normalize Standard Tile URL Source: https://github.com/openlayers/ol-mapbox-style/blob/main/_autodocs/mapbox-utilities-api.md Returns a standard tile URL as is. If a token is provided, it will be appended as a query parameter if the URL does not already contain one. ```javascript normalizeSourceUrl('https://example.com/tiles/{z}/{x}/{y}.pbf'); // Returns: ['https://example.com/tiles/{z}/{x}/{y}.pbf'] ```