ol-mapbox-style

repository·main·Indexed 19 days ago

https://github.com/openlayers/ol-mapbox-style

A library that allows developers to create OpenLayers layers or maps from Mapbox or MapLibre Style specifications. It translates style objects into OpenLayers layers, maps, and style functions, providing tools like MapboxVectorLayer for vector tiles and utilities for raster operations and hillshading.

Tokens
4.9K
Snippets
16
Records
29
Agent score
64%

What's inside ol-mapbox-style

  1. Configure webfonts for Mapbox/MapLibre styles

    main

    Because ol-mapbox-style uses web fonts instead of PBF/SDF glyphs, you must specify a location for webfonts. You can do this in two ways:

    1. Via Style Metadata: Set the ol:webfonts property in the root of the Style object.
    2. Via Options: Use the webfonts option in the apply() or applyStyle() functions.

    Template URL Placeholders:

    • {font-family}: CSS font family (lowercase, blanks replaced with -, e.g. noto-sans)
    • {Font+Family}: CSS font family (original case, blanks replaced with +, e.g. Noto+Sans)
    • {fontweight}: CSS font weight (numeric, e.g. 400)
    • {fontstyle}: CSS font style (e.g. normal, italic)
    • {-fontstyle}: CSS font style (e.g. -italic or empty string for normal)

    Font Stack Behavior: The library uses the primary font (the first in the stack) for style and weight. Subsequent fonts are used only as fallbacks if the primary font is unavailable, but they will inherit the style and weight of the primary font.

    {
      "version": 8,
      "metadata": {
        "ol:webfonts": "https://my.server/fonts/{font-family}/{fontweight}{-fontstyle}.css"
      }
      // ...
    }
  2. Install ol-mapbox-style

    main

    To use the library in an npm-based development environment, install it via npm.

    OpenLayers Version Compatibility:

    • ol-mapbox-style >=12.4 is required for OpenLayers >10.3.1.
    • ol-mapbox-style >=9 requires OpenLayers version >=7 & <11.
    • ol-mapbox-style 8 requires OpenLayers version >=6.13 & <7.
    npm install ol-mapbox-style
  3. Use the standalone build of ol-mapbox-style

    main

    If you are not using an npm-based environment, you can include the standalone build by adding dist/olms.js to your HTML page. The exported functions will be available on the global olms object (e.g., olms.apply(), olms.applyBackground()).

    Note: The standalone build depends on the full build of OpenLayers.

  4. Build and test the library

    main

    To build the library and run tests locally:

    • Build: npm run build (outputs to dist/)
    • Test: npm test
    • Debug Tests in Browser: npm run karma. Open the indicated host/port (e.g., http://localhost:9876/) and click 'DEBUG'.
    npm run build
    npm test
    npm run karma
  5. Create an entire OpenLayers map from a style URL

    main

    You can create an entire OpenLayers map instance by passing the string 'map' as the first argument to apply(), followed by the style URL.

    import { apply } from 'ol-mapbox-style';
    
    apply('map', 'https://api.mapbox.com/styles/v1/mapbox/bright-v9?access_token=YOUR_MAPBOX_TOKEN');
  6. Apply a Mapbox/MapLibre style to an OpenLayers LayerGroup

    main

    The recommended way to use a Mapbox or MapLibre style is to apply it to an OpenLayers LayerGroup. This allows you to add the group to an existing OpenLayers Map instance.

    import { apply } from 'ol-mapbox-style';
    import LayerGroup from 'ol/layer/Group.js'
    
    const liberty = new LayerGroup();
    apply(liberty, 'https://tiles.openfreemap.org/styles/liberty');
    
    // `map` is an OpenLayers Map instance
    map.addLayer(liberty);
  7. Assign style and source to a specific layer with applyStyle()

    main

    Use applyStyle() to apply a Mapbox/MapLibre style and source to an existing OpenLayers layer. This function supports mapbox:// URLs and accepts an options object (e.g., for accessToken).

    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'});
  8. Use the low-level stylefunction API

    main

    For fine-grained control, use the stylefunction module to create a style function for individual OpenLayers vector or vector tile layers.

    Note: This low-level API does not automatically create a source for the layer, and you must manually handle sprite/icon setup for styles that use them.

    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/states.geojson'
      })
    });
    
    fetch('data/states.json').then(function(response) {
      response.json().then(function(glStyle) {
        stylefunction(layer, glStyle, 'states');
      });
    });
  9. Configure MapboxVectorLayer options

    main

    When instantiating MapboxVectorLayer, you can provide an options object to control how the style is applied and how the layer behaves in OpenLayers.

    Key configuration options include:

    • styleUrl (Required): The URL of the Mapbox/MapLibre Style object (e.g., mapbox://styles/... or an https:// URL).
    • accessToken (Optional): The access token for Mapbox/MapLibre styles. Required for mapbox:// URLs. For https:// URLs, the key should be the last query parameter of the URL.
    • source (Optional): The ID of the specific vector source in the style to use.
    • layers (Optional): An array of layer names to include from the source. All must share the same source.
    • declutter (Optional): Boolean (default true). Declutters images and text. To opt out of the optimized ol-layer behavior, provide a different className.
    • background (Optional): Background color. Set to false to prevent the style's background from being used.
    • renderMode (Optional): 'hybrid' (default) or 'vector'. 'hybrid' renders polygons/lines as images for smooth zoom animations; 'vector' renders everything as vectors (better for few features).
    • renderBuffer (Optional): Pixel buffer around tile extent (default 100). Should match the largest possible buffer of the used tiles.
    new MapboxVectorLayer({
      styleUrl: 'https://example.com/style.json',
      accessToken: 'pk.your_token',
      source: 'my-vector-source-id',
      layers: ['roads', 'buildings'],
      renderMode: 'vector',
      declutter: true,
      background: 'rgba(255, 255, 255, 0.5)',
      opacity: 0.8
    });
  10. Use MapboxVectorLayer to create vector tile layers

    main

    The MapboxVectorLayer class creates an OpenLayers VectorTileLayer based on a Mapbox or MapLibre Style object. It is designed to work with a single vector source from the style.

    If your style contains multiple sources, you must use the source option to specify which vector source ID to use. Alternatively, you can use the layers option to limit rendering to a specific list of layer names, provided they all share the same vector source.

    Note for users of the full build: MapboxVectorLayer requires the ol-mapbox-style library to be loaded in your environment.

    import {MapboxVectorLayer} from 'ol-mapbox-style';
    
    const layer = new MapboxVectorLayer({
      styleUrl: 'mapbox://styles/mapbox/bright-v9',
      accessToken: 'your-mapbox-access-token-here',
    });
  11. Apply letter spacing to text

    main

    The applyLetterSpacing function simulates letter spacing in environments that do not natively support it by injecting hair spaces (\u200A) between characters. This is useful for map labels where a specific letterSpacing value is required from a Mapbox style.

    If letterSpacing is less than 0.05, the original text is returned without modification.

    import { applyLetterSpacing } from 'ol-mapbox-style/src/text.js';
    
    const spacedText = applyLetterSpacing('Hello World', 0.1);