Git Product home page Git Product logo

ol-mapbox-style's Introduction

ol-mapbox-style

Create OpenLayers maps from Mapbox Style Specification objects.

Getting started

Get an impression of what this library does by exploring the live examples.

Installation

To use the library in an application with an npm based dev environment, install it with

npm install ol-mapbox-style

When installed this way, just import the ol-mapbox-style module, like in the usage example below. To use a standalone build of ol-mapbox-style, just include 'dist/olms.js' on your HTML page, and access the exported functions from the global olms object (e.g. olms.apply(), olms.applyBackground()). Note that the standalone build depends on the full build of OpenLayers.

ol-mapbox-style >=v9 requires OpenLayers version >=7.

ol-mapbox-style v8 requires OpenLayers version >=6.13.0 <7.

Usage

See the API section for the full documentation.

The code below creates an OpenLayers map from Mapbox's Bright v9 style, using a https:// url:

import { apply } from 'ol-mapbox-style';

apply('map', 'https://api.mapbox.com/styles/v1/mapbox/bright-v9?access_token=YOUR_MAPBOX_TOKEN');

To assign style and source to a layer only, use applyStyle(). mapbox:// urls are also supported:

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

To apply the properties of the Mapbox Style's background layer to the map or a VectorTile layer, use the applyBackground() function.

There is also a low-level API available. To create a style function for individual OpenLayers vector or vector tile layers, use the stylefunction module:

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

Note that this low-level API does not create a source for the layer, and extra work is required to set up sprite handling for styles that use icons.

Compatibility notes

Font handling

ol-mapbox-style cannot use PBF/SDF glyphs for text-font layout property, as defined in the Mapbox Style specification. Instead, it relies on web fonts. A ol:webfonts metadata property can be set on the root of the Style object to specify a location for webfonts, e.g.

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

As an alternative, the webfonts option of the apply() or applyStyle() functions can be used.

The following placeholders can be used in the template url:

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

If no metadata['ol:webfonts'] property is available on the Style object, Fontsource Fonts will be used. It is also possible for the application to load other fonts, using css. If a font is already available in the browser, ol-mapbox-style will not load it.

Because of this difference, the font stack is treated a little different than defined in the spec: style and weight are taken from the primary font (i.e. the first one in the font stack). Subsequent fonts in the font stack are only used if the primary font is not available/loaded, and they will be used with the style and weight of the primary font.

Building the library

npm run build

The resulting distribution files will be in the dist/ folder. To see the library in action, navigate to dist/index.html.

To run test locally, run

npm test

For debugging tests in the browser, run

npm run karma

and open a browser on the host and port indicated in the console output (usually http://localhost:9876/) and click the 'DEBUG' button to go to the debug environment.

Test Job

API

ol-mapbox-style

Table of contents

References

Modules

Classes

Functions

References

default

Renames and re-exports apply

Functions

addMapboxLayer

addMapboxLayer(mapOrGroup, mapboxLayer, beforeLayerId?): Promise\<void>

Add a new Mapbox Layer object to the style. The map will be re-rendered.

Parameters
Name Type Description
mapOrGroup Map | LayerGroup The Map or LayerGroup apply was called on.
mapboxLayer any Mapbox Layer object.
beforeLayerId? string Optional id of the Mapbox Layer before the new layer that will be added.
Returns

Promise\<void>

Resolves when the added layer is available.


apply

apply(mapOrGroupOrElement, style, options?): Promise\<Map | LayerGroup>

Loads and applies a Mapbox Style object into an OpenLayers Map or LayerGroup. This includes the map background, the layers, and for Map instances that did not have a View defined yet also the center and the zoom.

Example:

import apply from 'ol-mapbox-style';

apply('map', 'mapbox://styles/mapbox/bright-v9', {accessToken: 'YOUR_MAPBOX_TOKEN'});

The center and zoom will only be set if present in the Mapbox Style document, and if not already set on the OpenLayers map.

Layers will be added to the OpenLayers map, without affecting any layers that might already be set on the map.

Layers added by apply() will have two additional properties:

  • mapbox-source: The id of the Mapbox Style document's source that the OpenLayers layer was created from. Usually apply() creates one OpenLayers layer per Mapbox Style source, unless the layer stack has layers from different sources in between.
  • mapbox-layers: The ids of the Mapbox Style document's layers that are included in the OpenLayers layer.

This function sets an additional mapbox-style property on the OpenLayers Map or LayerGroup instance, which holds the Mapbox Style object.

Parameters
Name Type Description
mapOrGroupOrElement string | Map | LayerGroup | HTMLElement Either an existing OpenLayers Map instance, or a HTML element, or the id of a HTML element that will be the target of a new OpenLayers Map, or a layer group. If layer group, styles releated to the map and view will be ignored.
style any JSON style object or style url pointing to a Mapbox Style object. When using Mapbox APIs, the url is the styleUrl shown in Mapbox Studio's "share" panel. In addition, the accessToken option (see below) must be set. When passed as JSON style object, all OpenLayers layers created by apply() will be immediately available, but they may not have a source yet (i.e. when they are defined by a TileJSON url in the Mapbox Style document). When passed as style url, layers will be added to the map when the Mapbox Style document is loaded and parsed.
options Options Options.
Returns

Promise\<Map | LayerGroup>

A promise that resolves after all layers have been added to the OpenLayers Map instance or LayerGroup, their sources set, and their styles applied. The resolve callback will be called with the OpenLayers Map instance or LayerGroup as argument.


applyBackground

applyBackground(mapOrLayer, glStyle, options?): Promise\<any>

Applies properties of the Mapbox Style's first background layer to the provided map or layer (group).

Example:

import {applyBackground} from 'ol-mapbox-style';
import {Map} from 'ol';

const map = new Map({target: 'map'});
applyBackground(map, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_OPENMAPTILES_TOKEN');
Parameters
Name Type Description
mapOrLayer Map | BaseLayer OpenLayers Map or layer (group).
glStyle any Mapbox Style object or url.
options Options Options.
Returns

Promise\<any>

Promise that resolves when the background is applied.


applyStyle

applyStyle(layer, glStyle, sourceOrLayersOrOptions?, optionsOrPath?, resolutions?): Promise\<any>

Applies a style function to an ol/layer/VectorTile or ol/layer/Vector with an ol/source/VectorTile or an ol/source/Vector. If the layer does not have a source yet, it will be created and populated from the information in the glStyle (unless updateSource is set to false).

Example:

import {applyStyle} from 'ol-mapbox-style';
import {VectorTile} from 'ol/layer.js';

const layer = new VectorTile({declutter: true});
applyStyle(layer, 'https://api.maptiler.com/maps/basic/style.json?key=YOUR_OPENMAPTILES_TOKEN');

The style function will render all layers from the glStyle object that use the source of the first layer, the specified source, or a subset of layers from the same source. The source needs to be a "type": "vector" or "type": "geojson" source.

Two additional properties will be set on the provided layer:

  • mapbox-source: The id of the Mapbox Style document's source that the OpenLayers layer was created from. Usually apply() creates one OpenLayers layer per Mapbox Style source, unless the layer stack has layers from different sources in between.
  • mapbox-layers: The ids of the Mapbox Style document's layers that are included in the OpenLayers layer.
Parameters
Name Type Default value Description
layer VectorLayer\<any> | VectorTileLayer\<any> undefined OpenLayers layer. When the layer has a source configured, it will be modified to use the configuration from the glStyle's source. Options specified on the layer's source will override those from the glStyle's source, except for url and tileUrlFunction. When the source projection is the default (EPSG:3857), the tileGrid will also be overridden. If you'd rather not have ol-mapbox-style modify the source, configure applyStyle() with the updateSource: false option.
glStyle any undefined Mapbox Style object.
sourceOrLayersOrOptions? string | string[] | Options & ApplyStyleOptions '' Options or source key or an array of layer ids from the Mapbox Style object. When a source key is provided, all layers for the specified source will be included in the style function. When layer ids are provided, they must be from layers that use the same source. When not provided or a falsey value, all layers using the first source specified in the glStyle will be rendered.
optionsOrPath? string | Options & ApplyStyleOptions {} Deprecated. Options. Alternatively the path of the style file (only required when a relative path is used for the "sprite" property of the style).
resolutions? number[] undefined Deprecated. Resolutions for mapping resolution to zoom level. Only needed when working with non-standard tile grids or projections, can also be supplied with options.
Returns

Promise\<any>

Promise which will be resolved when the style can be used for rendering.


getFeatureState

getFeatureState(mapOrLayer, feature): any

Sets or removes a feature state. The feature state is taken into account for styling, just like the feature's properties, and can be used e.g. to conditionally render selected features differently.

Parameters
Name Type Description
mapOrLayer Map | VectorLayer\<any> | VectorTileLayer\<any> Map or layer to set the feature state on.
feature FeatureIdentifier Feature identifier.
Returns

any

Feature state or null when no feature state is set for the given feature identifier.


getLayer

getLayer(map, layerId): Layer\<Source, LayerRenderer\<any>>

Get the OpenLayers layer instance that contains the provided Mapbox Style layer. Note that multiple Mapbox Style layers are combined in a single OpenLayers layer instance when they use the same Mapbox Style source.

Parameters
Name Type Description
map Map | LayerGroup OpenLayers Map or LayerGroup.
layerId string Mapbox Style layer id.
Returns

Layer\<Source, LayerRenderer\<any>>

OpenLayers layer instance.


getLayers

getLayers(map, sourceId): Layer\<Source, LayerRenderer\<any>>[]

Get the OpenLayers layer instances for the provided Mapbox Style source.

Parameters
Name Type Description
map Map | LayerGroup OpenLayers Map or LayerGroup.
sourceId string Mapbox Style source id.
Returns

Layer\<Source, LayerRenderer\<any>>[]

OpenLayers layer instances.


getMapboxLayer

getMapboxLayer(mapOrGroup, layerId): any

Get the Mapbox Layer object for the provided layerId.

Parameters
Name Type Description
mapOrGroup Map | LayerGroup Map or LayerGroup.
layerId string Mapbox Layer id.
Returns

any

Mapbox Layer object.


getSource

getSource(map, sourceId): Source

Get the OpenLayers source instance for the provided Mapbox Style source.

Parameters
Name Type Description
map Map | LayerGroup OpenLayers Map or LayerGroup.
sourceId string Mapbox Style source id.
Returns

Source

OpenLayers source instance.


getStyleForLayer

getStyleForLayer(feature, resolution, olLayer, layerId): Style[]

Get the the style for a specific Mapbox layer only. This can be useful for creating a legend.

Parameters
Name Type Description
feature Feature\<Geometry> | RenderFeature OpenLayers feature.
resolution number View resolution.
olLayer VectorLayer\<any> | VectorTileLayer\<any> OpenLayers layer.
layerId string Id of the Mapbox layer to get the style for
Returns

Style[]

Styles for the provided Mapbox layer.


recordStyleLayer

recordStyleLayer(record?): void

Turns recording of the Mapbox Style's layer on and off. When turned on, the layer that a rendered feature belongs to will be set as the feature's mapbox-layer property.

Parameters
Name Type Default value Description
record boolean false Recording of the style layer is on.
Returns

void


removeMapboxLayer

removeMapboxLayer(mapOrGroup, mapboxLayerIdOrLayer): void

Remove a Mapbox Layer object from the style. The map will be re-rendered.

Parameters
Name Type Description
mapOrGroup Map | LayerGroup The Map or LayerGroup apply was called on.
mapboxLayerIdOrLayer any Mapbox Layer id or Mapbox Layer object.
Returns

void


renderTransparent

renderTransparent(enabled): void

Configure whether features with a transparent style should be rendered. When set to true, it will be possible to hit detect content that is not visible, like transparent fills of polygons, using ol/layer/Layer#getFeatures() or ol/Map#getFeaturesAtPixel()

Parameters
Name Type Description
enabled boolean Rendering of transparent elements is enabled. Default is false.
Returns

void


setFeatureState

setFeatureState(mapOrLayer, feature, state): void

Sets or removes a feature state. The feature state is taken into account for styling, just like the feature's properties, and can be used e.g. to conditionally render selected features differently.

The feature state will be stored on the OpenLayers layer matching the feature identifier, in the mapbox-featurestate property.

Parameters
Name Type Description
mapOrLayer Map | VectorLayer\<any> | VectorTileLayer\<any> OpenLayers Map or layer to set the feature state on.
feature FeatureIdentifier Feature identifier.
state any Feature state. Set to null to remove the feature state.
Returns

void


stylefunction

stylefunction(olLayer, glStyle, sourceOrLayers, resolutions?, spriteData?, spriteImageUrl?, getFonts?, getImage?, ...args): StyleFunction

Creates a style function from the glStyle object for all layers that use the specified source, which needs to be a "type": "vector" or "type": "geojson" source and applies it to the specified OpenLayers layer.

Two additional properties will be set on the provided layer:

  • mapbox-source: The id of the Mapbox Style document's source that the OpenLayers layer was created from. Usually apply() creates one OpenLayers layer per Mapbox Style source, unless the layer stack has layers from different sources in between.
  • mapbox-layers: The ids of the Mapbox Style document's layers that are included in the OpenLayers layer.

This function also works in a web worker. In worker mode, the main thread needs to listen to messages from the worker and respond with another message to make sure that sprite image loading works:

 worker.addEventListener('message', event => {
  if (event.data.action === 'loadImage') {
    const image = new Image();
    image.crossOrigin = 'anonymous';
    image.addEventListener('load', function() {
      createImageBitmap(image, 0, 0, image.width, image.height).then(imageBitmap => {
        worker.postMessage({
          action: 'imageLoaded',
          image: imageBitmap,
          src: event.data.src
        }, [imageBitmap]);
      });
    });
    image.src = event.data.src;
  }
});
Parameters
Name Type Default value Description
olLayer VectorLayer\<any> | VectorTileLayer\<any> undefined OpenLayers layer to apply the style to. In addition to the style, the layer will get two properties: mapbox-source will be the id of the glStyle's source used for the layer, and mapbox-layers will be an array of the ids of the glStyle's layers.
glStyle any undefined Mapbox Style object.
sourceOrLayers string | string[] undefined source key or an array of layer ids from the Mapbox Style object. When a source key is provided, all layers for the specified source will be included in the style function. When layer ids are provided, they must be from layers that use the same source.
resolutions number[] defaultResolutions Resolutions for mapping resolution to zoom level.
spriteData any undefined Sprite data from the url specified in the Mapbox Style object's sprite property. Only required if a sprite property is specified in the Mapbox Style object.
spriteImageUrl string | Request | Promise\<string | Request> undefined Sprite image url for the sprite specified in the Mapbox Style object's sprite property. Only required if a sprite property is specified in the Mapbox Style object.
getFonts (arg0: string[], arg1: string) => string[] undefined Function that receives a font stack and the url template from the GL style's metadata['ol:webfonts'] property (if set) as arguments, and returns a (modified) font stack that is available. Font names are the names used in the Mapbox Style object. If not provided, the font stack will be used as-is. This function can also be used for loading web fonts.
getImage? (arg0: VectorLayer\<any> | VectorTileLayer\<any>, arg1: string) => string | HTMLCanvasElement | HTMLImageElement undefined Function that returns an image or a URL for an image name. If the result is an HTMLImageElement, it must already be loaded. The layer can be used to call layer.changed() when the loading and processing of the image has finished. This function can be used for icons not in the sprite or to override sprite icons.
...args any undefined -
Returns

StyleFunction

Style function for use in ol.layer.Vector or ol.layer.VectorTile.


updateMapboxLayer

updateMapboxLayer(mapOrGroup, mapboxLayer): void

Update a Mapbox Layer object in the style. The map will be re-rendered with the new style.

Parameters
Name Type Description
mapOrGroup Map | LayerGroup The Map or LayerGroup apply was called on.
mapboxLayer any Updated Mapbox Layer object.
Returns

void


updateMapboxSource

updateMapboxSource(mapOrGroup, id, mapboxSource): Promise\<Source>

Updates a Mapbox source object in the style. The according OpenLayers source will be replaced and the map will be re-rendered.

Parameters
Name Type Description
mapOrGroup Map | LayerGroup The Map or LayerGroup apply was called on.
id string Key of the source in the sources object literal.
mapboxSource any Mapbox source object.
Returns

Promise\<Source>

Promise that resolves when the source has been updated.

Class: MapboxVectorLayer

Classdesc

import {MapboxVectorLayer} from 'ol-mapbox-style';

A vector tile layer based on a Mapbox style that uses a single vector source. Configure the layer with the styleUrl and accessToken shown in Mapbox Studio's share panel. If the style uses more than one source, use the source property to choose a single vector source. If you want to render a subset of the layers in the style, use the layers property (all layers must share the same vector source). See the constructor options for more detail.

const map = new Map({
  view: new View({
    center: [0, 0],
    zoom: 1,
  }),
  layers: [
    new MapboxVectorLayer({
      styleUrl: 'mapbox://styles/mapbox/bright-v9',
      accessToken: 'your-mapbox-access-token-here',
    }),
  ],
  target: 'map',
});

On configuration or loading error, the layer will trigger an 'error' event. Listeners will receive an object with an error property that can be used to diagnose the problem.

Note for users of the full build: The MapboxVectorLayer requires the ol-mapbox-style library to be loaded as well.

Param

Options.

Fires

module:ol/events/Event~BaseEvent#event:error

Api

Hierarchy

  • VectorTileLayer

    MapboxVectorLayer

Table of contents

Constructors

Properties

Constructors

constructor

new MapboxVectorLayer(options): MapboxVectorLayer

Parameters
Name Type Description
options Options Layer options. At a minimum, styleUrl and accessToken must be provided.
Returns

MapboxVectorLayer

Overrides

VectorTileLayer.constructor

Properties

accessToken

accessToken: string

Interface: ApplyStyleOptions\<>

\<internal>.ApplyStyleOptions

Table of contents

Properties

Properties

layers

layers: string[]

Layers. If no source is provided, the layers with the provided ids will be used from the style's layers array. All layers need to use the same source.


source

source: string

Source. Default is '', which causes the first source in the style to be used.


updateSource

updateSource: boolean

Update or create vector (tile) layer source with parameters specified for the source in the mapbox style definition.

Interface: FeatureIdentifier\<>

\<internal>.FeatureIdentifier

Table of contents

Properties

Properties

id

id: string | number

The feature id.


source

source: string

The source id.

Interface: Options\<>

\<internal>.Options

Table of contents

Properties

Properties

accessToken

accessToken: string

The access token for your Mapbox style. This has to be provided for mapbox:// style urls. For https:// and other urls, any access key must be the last query parameter of the style url.


background

background: false | BackgroundColor

Background color for the layer. If not specified, the background from the Mapbox style object will be used. Set to false to prevent the Mapbox style's background from being used.


className

className: string

A CSS class name to set to the layer element.


declutter

declutter: boolean

Declutter images and text. Decluttering is applied to all image and text styles of all Vector and VectorTile layers that have set this to true. The priority is defined by the z-index of the layer, the zIndex of the style and the render order of features. Higher z-index means higher priority. Within the same z-index, a feature rendered before another has higher priority.

As an optimization decluttered features from layers with the same className are rendered above the fill and stroke styles of all of those layers regardless of z-index. To opt out of this behavior and place declutterd features with their own layer configure the layer with a className other than ol-layer.


extent

extent: Extent

The bounding extent for layer rendering. The layer will not be rendered outside of this extent.


layers

layers: string[]

Limit rendering to the list of included layers. All layers must share the same vector source. If your style uses more than one source, you need to use either the source property or the layers property to limit rendering to a single vector source.


map

map: Map

Sets the layer as overlay on a map. The map will not manage this layer in its layers collection, and the layer will be rendered on top. This is useful for temporary layers. The standard way to add a layer to a map and have it managed by the map is to use map.addLayer().


maxResolution

maxResolution: number

The maximum resolution (exclusive) below which this layer will be visible. If neither maxResolution nor minZoom are defined, the layer's maxResolution will match the style source's minzoom.


maxZoom

maxZoom: number

The maximum view zoom level (inclusive) at which this layer will be visible.


minResolution

minResolution: number

The minimum resolution (inclusive) at which this layer will be visible.


minZoom

minZoom: number

The minimum view zoom level (exclusive) above which this layer will be visible. If neither maxResolution nor minZoom are defined, the layer's minZoom will match the style source's minzoom.


opacity

opacity: number

Opacity (0, 1).


preload

preload: number

Preload. Load low-resolution tiles up to preload levels. 0 means no preloading.


properties

properties: Object

Arbitrary observable properties. Can be accessed with #get() and #set().


renderBuffer

renderBuffer: number

The buffer in pixels around the tile extent used by the renderer when getting features from the vector tile for the rendering or hit-detection. Recommended value: Vector tiles are usually generated with a buffer, so this value should match the largest possible buffer of the used tiles. It should be at least the size of the largest point symbol or line width.


renderMode

renderMode: VectorTileRenderType

Render mode for vector tiles:

  • 'hybrid': Polygon and line elements are rendered as images, so pixels are scaled during zoom animations. Point symbols and texts are accurately rendered as vectors and can stay upright on rotated views.
  • 'vector': Everything is rendered as vectors. Use this mode for improved performance on vector tile layers with only a few rendered features (e.g. for highlighting a subset of features of another layer with the same source).

renderOrder

renderOrder: OrderFunction

Render order. Function to be used when sorting features before rendering. By default features are drawn in the order that they are created. Use null to avoid the sort, but get an undefined draw order.


source

source: string

If your style uses more than one source, you need to use either the source property or the layers property to limit rendering to a single vector source. The source property corresponds to the id of a vector source in your Mapbox style.


styleUrl

styleUrl: string

The URL of the Mapbox style object to use for this layer. For a style created with Mapbox Studio and hosted on Mapbox, this will look like 'mapbox://styles/you/your-style'.


updateWhileAnimating

updateWhileAnimating: boolean

When set to true, feature batches will be recreated during animations. This means that no vectors will be shown clipped, but the setting will have a performance impact for large amounts of vector data. When set to false, batches will be recreated when no animation is active.


updateWhileInteracting

updateWhileInteracting: boolean

When set to true, feature batches will be recreated during interactions. See also updateWhileAnimating.


useInterimTilesOnError

useInterimTilesOnError: boolean

Use interim tiles on error.


visible

visible: boolean

Visibility.


zIndex

zIndex: number

The z-index for layer rendering. At rendering time, the layers will be ordered, first by Z-index and then by position. When undefined, a zIndex of 0 is assumed for layers that are added to the map's layers collection, or Infinity when the layer's setMap() method was used.

Interface: Options\<>

\<internal>.Options

Table of contents

Properties

Properties

accessToken

accessToken: string

Access token for 'mapbox://' urls.


accessTokenParam

accessTokenParam: string

Access token param. For internal use.


getImage

getImage: (arg0: VectorLayer\<any> | VectorTileLayer\<any>, arg1: string) => string | HTMLCanvasElement | HTMLImageElement

Function that returns an image for an icon name. If the result is an HTMLImageElement, it must already be loaded. The layer can be used to call layer.changed() when the loading and processing of the image has finished. This function be used for icons not in the sprite or to override sprite icons.

Type declaration

▸ (arg0, arg1): string | HTMLCanvasElement | HTMLImageElement

Parameters
Name Type
arg0 VectorLayer\<any> | VectorTileLayer\<any>
arg1 string
Returns

string | HTMLCanvasElement | HTMLImageElement


projection

projection: string

Only useful when working with non-standard projections. Code of a projection registered with OpenLayers. All sources of the style must be provided in this projection. The projection must also have a valid extent defined, which will be used to determine the origin and resolutions of the tile grid for all tiled sources of the style. When provided, the bbox placeholder in tile and geojson urls changes: the default is {bbox-epsg-3857}, when projection is e.g. set to EPSG:4326, the bbox placeholder will be {bbox-epsg-4326}.


resolutions

resolutions: number[]

Only useful when working with non-standard projections. Resolutions for mapping resolution to the zoom used in the Mapbox style.


styleUrl

styleUrl: string

URL of the Mapbox GL style. Required for styles that were provided as object, when they contain a relative sprite url, or sources referencing data by relative url.


transformRequest

transformRequest: (arg0: string, arg1: ResourceType) => string | void | Request | Promise\<string | Request>

Function for controlling how ol-mapbox-style fetches resources. Can be used for modifying the url, adding headers or setting credentials options. Called with the url and the resource type as arguments, this function is supposed to return a Request or a url string, or a promise tehereof. Without a return value the original request will not be modified.

Type declaration

▸ (arg0, arg1): string | void | Request | Promise\<string | Request>

Parameters
Name Type
arg0 string
arg1 ResourceType
Returns

string | void | Request | Promise\<string | Request>


webfonts

webfonts: string

Template for resolving webfonts. Can be used to specify where to fetch web fonts when no ol:webfonts metadata is set in the style object. See getFonts() and the "Font handling" section in README.md for details.

Module: \<internal>

Table of contents

Interfaces

Type Aliases

Type Aliases

ResourceType

Ƭ ResourceType\<>: "Style" | "Source" | "Sprite" | "SpriteImage" | "Tiles" | "GeoJSON"

ol-mapbox-style's People

Contributors

ahocevar avatar alenkelemen avatar bartvde avatar bovandersteene avatar chrismayer avatar christiankohler avatar cns-solutions-admin avatar dependabot[bot] avatar egaoneko avatar ejn avatar eliask avatar fleur avatar frankrowe avatar fredj avatar gd-aichi avatar harelm avatar jnystad avatar m393 avatar mike-000 avatar orangemug avatar pakb avatar petrsloup avatar robertorthofer avatar songyumeng avatar tbarsballe avatar theduckylittle avatar toddwong avatar tschaub avatar v-roger avatar walkermatt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ol-mapbox-style's Issues

serialized styles output

It would be nice to be able to generate a regular OL Style descriptor as a string. Could then just be copied into the code and wouldn´t make it necessary to deliver your lib in production (at least for static styles).
Do you think that would make sense?

Example VectorTile Styling Needed

Using an old version of the library I get to work mapbox styles but in a slowly way. Now, I am using the last version of this library but I don't see how I do to make it work.

I am doing something like this:

Layer definition

const vtLayer = new ol.layer.VectorTileLayer({
 declutter: true,
 renderMode: 'image',
 renderBuffer: 2,
 source: new ol.source.VectorTileSource({
   format: new ol.format.MVT(),
   overlaps: false,
   url: 'http://10.0.2.93:8080/geoserver/gwc/service/tms/1.0.0/bl:B_PARC@EPSG:900913@pbf/{z}/{x}/{-y}.pbf?1537872297191'
 })
});
  • note that I am using my own Geoserver as a MVT server

VT Style definition

var stylelyrs= {
    "version": 8,
    "name": "test",
   "sources": {
     "test": {
        "type": "vector"
      }
    },
    "layers": [{
        "id": "bl:B_PARC",
        "type": "fill",
        "source": "bl:B_PARC",
        "paint": {
          "fill-color": "#00cc00",
          "fill-opacity": 0.6,
          "line-color": "#004d00",
          "line-width": 1
        }
}]
  };

Assigning style function

 olms.stylefunction(vtLayer, stylelyrs, 'bl:B_PARC');

pbf's are loading behind but I can't see any geometry on my map, I guess it must be something related with olms applyiing style (as I said, with old version is working - getStyleFunction method). Do you know why is not working with the newest? Do you have more examples or documentation?

Thank you.

Prepare for "mapbox-gl-style-spec" package changes

Hello!

I work on at Mapbox on Mapbox GL. We are preparing to make some changes to the mapbox-gl-style-spec package which may affect you:

  • the mapbox-gl-style-spec package will be deprecated and replaced by @mapbox/mapbox-gl-style-spec
  • mapbox-gl-style-spec package will begin using es6 features, requiring the use of transpilation (if you're using browserify, this'll happen automatically via bubleify)
  • the file structure of mapbox-gl-style-spec will change (which will affect the use of require(mapbox-gl-style-spec/lib/**/*.js))

You can read more about these changes at mapbox/mapbox-gl-js#3946 and mapbox/mapbox-gl-js#3656.

Let me know if you have any questions or need any help!

Arcgıs vector tile - font problem

Hi ,I am using olms to load arcgis style in my ol vector tile.
I use many fonts . some fonts can not be displayed correctly

how can i solve this problem ?

Thank You :)

eslint is not checking the source code

In package.json, the pretest is:

eslint src & npm run test-bundle

But there's not src directory. Shouldn't it be changed to something like:

eslint index.js & npm run test-bundle

Console Module parse errors when compiling in Angular project

I import latest ol and ol-mapbox-style pakcage, and I only write one line code 'apply('map', this.serverHost + 'event_didi.json');', but error occured when compiling.

ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/util/color.js
Module parse failed: Unexpected token (17:5)
You may need an appropriate loader to handle this file type.
| */
| class Color {
| r: number;
| g: number;
| b: number;
ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/expression/index.js
Module parse failed: Unexpected token (19:12)
You may need an appropriate loader to handle this file type.
| import { success, error } from '../util/result';
|
| import type {Type} from './types';
| import type {Value} from './values';
| import type {Expression} from './expression';
ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/feature_filter/index.js
Module parse failed: Unexpected token (5:12)
You may need an appropriate loader to handle this file type.
| import { createExpression } from '../expression';
|
| import type {GlobalProperties} from '../expression';
| export type FeatureFilter = (globalProperties: GlobalProperties, feature: VectorTileFeature) => boolean;
|
ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/util/interpolate.js
Module parse failed: Unexpected token (5:24)
You may need an appropriate loader to handle this file type.
| import Color from './color';
|
| export function number(a: number, b: number, t: number) {
| return (a * (1 - t)) + (b * t);
| }
ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/function/convert.js
Module parse failed: Unexpected token (7:12)
You may need an appropriate loader to handle this file type.
| import extend from '../util/extend';
|
| import type {StylePropertySpecification} from '../style-spec';
|
| export default convertFunction;
ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/util/color_spaces.js
Module parse failed: Unexpected token (7:5)
You may need an appropriate loader to handle this file type.
| import {number as interpolateNumber} from './interpolate';
|
| type LABColor = {
| l: number,
| a: number,
ERROR in ./node_modules/@mapbox/mapbox-gl-style-spec/expression/definitions/interpolate.js
Module parse failed: Unexpected token (9:12)
You may need an appropriate loader to handle this file type.
| import { findStopLessThanOrEqualTo } from '../stops';
|
| import type { Stops } from '../stops';
| import type { Expression } from '../expression';
| import type ParsingContext from '../parsing_context';

Issue with Maputnik style

Hi, i used Maputnik to create a new style object: http://192.168.1.55:8080/styles/klokantech-basic.json

I'm using webpack to bundle the source (ol 4.1.0) and try to build a map inside a react app like so:

this.map = new Map({target: this.map_wrapper});
apply(this.map, 'http://192.168.1.55:8080/styles/klokantech-basic.json');

and I get the following error
image

I'm a bit none-plussed about what is causing this error - any help is much appreciated!

stylefunction.js' fromTemplate might receive an array

Hiya,

Just came across this issue where the stylefunction.js' fromTemplate function receives an array as it's text argument, therefore it throws a wobbly.

Uncaught TypeError: text.match is not a function

Within Mapbox Studio one might use a function (to-string()) to convert non-string fields to string fields and use those as labels, hence the issue.

The text argument looks something like this:

["to-string", ["get", "<attributeName>"]]

A quick and dirty workaround can look like this:

if (Array.isArray(text) && text.length === 2 && text[0] === 'to-string' && Array.isArray(text[1]) && text[1].length === 2 && text[1][0] === 'get') {
  text = properties[text[1][1]].toString();
}

type background can be anywhere in the stack

AFAICT from testing with mapbox GL JS it seems that the assumption we make in ol-mapbox-style is incorrect, i.e. the type background layer can be anywhere in the stack, not just at the bottom

Build with react-build fails

Hi,

Using this package in a react app, when i try to build for prod, i've got the following error :

`

npm run build

[email protected] build /app/front
react-scripts build

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

   ./node_modules/@mapbox/mapbox-gl-style-spec/function/index.js:15 

`

(npm run build launch react-scripts build)

I'm trying to solve that problem. If you have any clue on what's happening. I'm not a master on npm builds.

Thanks.

visibility not respected on tile layers

For instance if I modify wms.json to:

      "id": "states-wms",
      "source": "states",
      "layout": {
        "visibility": "none"
      }

it is not taken into account. Same applies to osm in that same file.

text-opacity zoom properties not supported

I'm just trying out this library, and it looks great, but there's an obvious issue with labels showing up at the wrong zooms.

Mapbox-gl-js (zoom 13):

screenshot 2018-01-04 16 26 36

ol-mapbox-style (zoom 14):

screenshot 2018-01-04 16 26 51

One of the layers that shouldn't be displaying (containing the churches, primary schools etc) is defined thus:

    {
      "id": "foi-label",
      "type": "symbol",
      "source": "VMFEAT",
      "source-layer": "foi_index_centroid",
      "filter": [
        "!in",
        "FTYPE",
        "sign",
        "care facility",
        "residential building",
        "community venue",
        "communication service"
      ],
      "layout": {
        "text-field": "{NAME_LABEL}",
        "text-size": 10,
        "text-max-width": 6
      },
      "paint": {
        "text-color": {
          "property": "FTYPE",
          "type": "categorical",
          "default": "green",
          "stops": [
            [
              "reserve",
              "green"
            ],
            [
              "education centre",
              "hsl(30, 50%, 50%)"
            ],
            [
              "place of worship",
              "hsl(30, 50%, 50%)"
            ],
            [
              "dumping ground",
              "hsl(0, 0%, 50%)"
            ],
            [
              "hospital",
              "hsl(0, 50%, 50%)"
            ]
          ]
        },
        "text-opacity": {
          "stops": [
            [
              14.5,
              0
            ],
            [
              15,
              1
            ]
          ]
        },
        "text-halo-width": 1,
        "text-halo-color": "hsla(0, 0%, 100%, 70%)"
      }
    },

AFAIK, using text-opacity like this is the recommended way to have a layer only show up above a certain zoom level in mapbox-gl-js. Is there a workaround in ol-mapbox-style, perhaps minzoom?

webpack Module parse failed

Version
3.0.0-beta.7 - work fine
but "ol-mapbox-style": "^3.0.0-beta.9" - generate errors

webpack-dev-server --inline --progress --config build/webpack.dev.conf.js

ERROR Failed to compile with 7 errors13:15:45

error in ./node_modules/@mapbox/mapbox-gl-style-spec/util/color.js

Module parse failed

: Unexpected token (17:5)
You may need an appropriate loader to handle this file type.
| */
| class Color {
| r: number;
| g: number;
| b: number;

@ ./node_modules/ol-mapbox-style/index.js 23:0-60
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/pages/OlMap/OlMap.vue
@ ./src/components/pages/OlMap/OlMap.vue
@ ./src/router/index.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?https://localhost:8080 webpack/hot/dev-server ./src/main.js

and etc. see atachment
rr.txt

How about add 'resolutions' parameter to 'applyStyle' function?

Hi, I have some vector tiles are not well displayd, I found that the reason of it is the resolutions. My vectorTiles ues different resolutions.
image.

I saw the code and found that
image
"applyStyleFunction" function supports "resolutions" parameter, but "onchange" function passed "undefined" to it.

If possible i want to add a "resolutions" parameter to "applyStyle" function , and pass it to "applyStyleFunction"

image

Create Vector Tile Layers Automatically

For users that just want to display a Mapbox GL style JSON with ol-mapbox-style there could be a more convenient higher level API.

Perhaps something like this. Ideally just passing the style URL.

var olms = require('ol-mapbox-style');
olms.addStyleLayer('https://raw.githubusercontent.com/openmaptiles/osm-bright-gl-style/master/style.json');

Would this be something that would fit into this repo? Otherwise I would put it into another repo which includes ol-mapbox-style.

In Maputnik right now I generate the vector sources dynamically (it is quite a hack though) for ol-mapbox-style but I would also like that users have this functionality when they use the style with OL3.

This would be an additional higher level API that takes care of:

  • Fetching the style
  • Resolving TileJSON
  • Create the layer
  • Create and apply the style func

I execute command 'npm install' in Mac OS but result failed and console pkg-config: command not found,

node-gyp rebuild

./util/has_lib.sh: line 31: pkg-config: command not found
gyp: Call to './util/has_lib.sh freetype' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: gyp failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:345:16)
gyp ERR! stack at ChildProcess.emit (events.js:182:13)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:238:12)
gyp ERR! System Darwin 16.7.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/didi/wanglei/codes/styles/ol-mapbox-style/node_modules/canvas
gyp ERR! node -v v10.8.0
gyp ERR! node-gyp -v v3.7.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/didi/.npm/_logs/2018-08-20T04_01_11_568Z-debug.log

olms with arcgis vector tile - Sprite failure

Hı ,
I am using olms to load arcgis style in my ol vector tile. I have two basic problems.

  1. Some icons do not appear in a certain zoom range.
    just max appears at zoom level.

in fact ==>
esri

ol-mapbox-style ==>
sh

  1. some icons do not appear in the correct position.

in fact ==>
esri 2

ol-mapbox-style ==>
sh2

Help me with your suggestions :)

AMD module

Is it possible to use this library as AMD module? Now I get erros about not found files from this section of code:

if (typeof define === 'function' && define.amd) {
    define([
        "_",
        "ol/observable",
        "ol/proj",
        "ol/tilegrid",
        "ol/map",
        "ol/format/geojson",
        "ol/format/mvt",
        "ol/layer/tile",
        "ol/layer/vector",
        "ol/layer/vectortile",
        "ol/source/tilejson",
        "ol/source/vector",
        "ol/source/xyz",
        "ol/source/vectortile",
        "ol/style/style",
        "ol/style/fill",
        "ol/style/stroke",
        "ol/style/circle"
], f.bind(_g, r))
} 

Does it make sense to add support of passing ol object to ol-mapbox-style?

Zoom-based fill-opacity issue on certain zoom levels

If fill-opacity is zoom-based (uses stops), black polygons appear instead of parks, nature reserves, buildings, towns etc. with their correct color codes.

"fill-opacity": {
    "stops": [
        [
            6,
            0.7
        ],
        [
            9,
            0.9
        ]
    ]
}

My current workaround is using a constant, then the issue does not appear:

"fill-opacity": 1,

The style I am trying to use is available at: https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json (there are several places where fill-opacity needs to be changed)

Sample javascript to reproduce the issue:

var baseUrl = 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json'; 
// var baseUrl = 'voyager.json';
var map = olms.apply('map', baseUrl);

Most likely culprit is alpha interpolation, but so far I have been unable to find the exact issue.

Image of issue:
screen shot 2017-11-23 at 15 17 29

cannot build olms.js due to canvas dependencies

I have a problem to build the lib.
When I do a npm install, the process is stopped to the canvas install.

C:\Users\xxx.node-gyp\6.10.0\include\node\v8.h(19): fatal error C1083: Impossible d'ouvrir le fichier include : 'stdint.h' : No such file or directory [C:\Users\xxx\Downloads\ol-mapbox-style3.3.0\node_modules\canvas\build\binding.sln]

Could you help me please ?

thx

the 'TileJSON vector tiles' example is not working

FYI. This is on the master tree. It references the URL https://osm.tegola.io/capabilities/osm.json and fails due to CORS headers. It appears the URL is no longer available:

$ wget https://osm.tegola.io/capabilities/osm.json
--2018-10-16 14:11:12--  https://osm.tegola.io/capabilities/osm.json
Resolving osm.tegola.io (osm.tegola.io)... 52.85.201.42, 52.85.201.10, 52.85.201.59, ...
Connecting to osm.tegola.io (osm.tegola.io)|52.85.201.42|:443... connected.
HTTP request sent, awaiting response... 503 Service Unavailable
2018-10-16 14:11:12 ERROR 503: Service Unavailable.

olms with arcgis vector tile - doubt/help

Hi ,I am using olms to load arcgis style in my ol vector tile. there i have set max zoom to 15. but some of the .pbf request at certain areas fails at zoom level 14 and map gets blurred. i am not sure this is the right place to post. Help me with your suggestions :)

toggle multiple styles

Hi

I'm trying to get a map to display with multiple styles of map ( street / satellite )
I can get the map to load with a single style... and i have also added some button which then ADD the other style. However i want the previous style to be removed.

`var satJson = 'https://maps.tilehosting.com/styles/hybrid/style.json?key=[MYKEYGOESHERE]' ;
var styleJson = 'content/mapping/openmaptiles-street/style-basic-original.json';

var map_view = new ol.View({
center: ol.proj.fromLonLat([-1.0, 53]),
zoom: 16
})

    var map = new ol.Map({
     target: 'map',
    view: map_view
});

olms.apply(map, satJson);`

how would i go about toggle between the 2 styles?

Thanks

Transparent polygon fill in stylesheet has no hit detection

With the update to the polygon fill hit detection in openlayers/openlayers#7750, I cannot set a fill-color to have a 0 opacity or fill-opacity: 0 within a stylesheet and have any kind of hit detection within a polygon. When the styles are converted into a style function through this package, it treats a 0 opacity polygon fill instead as having no fill and so no hit is detected.

fails to install due to missing dependency mapbox-gl-style-spec

Hi was looking forward to trying react-openlayers out but it won't npm install because it depends on ol-mapbox-style - and ol-mapbox-style won't install because your dependency mapbox-gl-style-spec is gone(?)

i.e. It appears the mapbox-gl-style-spec repo is now just a placeholder see:
https://github.com/mapbox/mapbox-gl-style-spec

It says: "This repository has been merged with mapbox-gl-js"

Here's my full install ouput JIC it helps:

npm install react-openlayers --save-dev
npm ERR! Darwin 15.6.0
npm ERR! argv "/Users/dcrus/.nvm/versions/node/v6.10.0/bin/node" "/Users/dcrus/.nvm/versions/node/v6.10.0/bin/npm" "install" "react-openlayers" "--save-dev"
npm ERR! node v6.10.0
npm ERR! npm v3.10.10
npm ERR! code E404

npm ERR! 404 Not found : @mapbox/mapbox-gl-style-spec
npm ERR! 404
npm ERR! 404 '' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 It was specified as a dependency of 'ol-mapbox-style'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/dcrus/field-maps-nav/npm-debug.log

Usage with Tileserver GL map server

Hello,
I am using Tileserver GL and/or Tileserver GL light to serve vector tiles.
I ran into two an issues with ol-mapbox-style :

  • I don't have an "access_token" in the sprite URL parameters, but I have a "style" parameter leading to malformed URL when getting sprites files ".json" and ".png". I think this can be resolved using this regex : var spriteRegEx = /^(.*)(\?.*)$/;
  • I have an openlayers error when using apply function. I found that the URL used in processStyle (url = glSource.url; line 252) is in fact a TileJSON URL http://127.0.0.1/data/planet.json with Tileserver. The vector URL can be accessed using TileJSON URL {"tiles":["http://127.0.0.1/data/planet/{z}/{x}/{y}.pbf"], ...}

Are those Is this issues only related to Tileserver GL? Is it possible to make a patch for the first issue (I was able to work around the second issue using applyBackground and applyStyle)?

Publish to npm

I know it this is still not production ready but could you publish ol-mapbox-gl-style to npm?

BTW. I am really amazed by this project. Hope to contribute. This could be the corner stone of building an style editor for OL3. maplibre/maputnik#7

Applying a style with EPSG:4326 Projection

Hello,
I have a OL5 map using a projection of EPSG:4326. I am adding a Vector Tile layer with a projection of ESPG:4326.

When I am using OLMS to apply a style to my Vector Tile I am seeing weird issues with how the styling is being rendered. I am assuming there is a disconnect with the Vector Tile Styling data vs the projection my map supports.

Any idea on why the below code does not seem to style the Vector Tile correctly? Is this a issue with the plugin or a issue with the way the layer is configured.

// Create vector tile layer
var layer = new ol.layer.VectorTile({
    source: new ol.source.VectorTile({
    format: new ol.format.MVT({ featureClass: ol.render.Feature }),
   url: 'https://basemaps.arcgis.com/v1/arcgis/rest/services/World_Basemap/VectorTileServer/tile/{z}/{y}/{x}.pbf',
   projection: ol.proj.get("EPSG:4326")
   })
});
// Create map
var map = new ol.Map({
	target: 'map',
	view: new ol.View({
	   projection: 'EPSG:4326',
	   center: [0, 0],
	   zoom: 2
	}),
	layers: [layer]
});

// Get style
$.get("https://www.arcgis.com/sharing/rest/content/items/291da5eab3a0412593b66d384379f89f/resources/styles/root.json")
   .then(function(res) {
	olms.applyStyle(layer, res, "esri");
});

vt

Angular 5 compatibility

Hi, do you experienced any incompatibility with Angular 5 and the latest Openlayers version?

I'm getting a

ERROR TypeError: targetElement.appendChild is not a function
    at _ol_Map_._ol_PluggableMap_.handleTargetChanged_ (pluggablemap.js:817)
    at _ol_Map_.boundListener (events.js:16)
    at _ol_Map_._ol_events_EventTarget_.dispatchEvent (eventtarget.js:77)
    at _ol_Map_._ol_Object_.notify (object.js:120)
    at _ol_Map_._ol_Object_.set (object.js:139)
    at _ol_Map_._ol_Object_.setProperties (object.js:153)
    at _ol_Map_._ol_PluggableMap_ [as constructor] (pluggablemap.js:241)
    at new _ol_Map_ (map.js:92)
    at c.apply (index.js:452)
    at AppComponent.ngOnInit

as soon as I call the apply on a simple map with one vector layer.

I'm trying to replicate the issue on stackblitz to help you understand what happens but in the meanwhile I was wondering if already know that I will not solve the issue.

Thanks.

Patched Mapbox GL Spec

@ahocevar Would it make sense to have a patched Mapbox GL spec that only contains the properties and layer types that are supported by ol-mapbox-style?

I would take care of it. It could be in this repo or in another one.

For https://github.com/maputnik/editor this would allow me to only display properties for a OL3 style that can be supported.
And in general it would help to specify and document the subset of the Mapbox GL spec that is supported by ol-mapbox-style.

As always - I love this plugin.

"Can't resolve 'isomorphic-fetch' in path\node_modules\ol-mapbox-style"

Hi, I'm trying to implement a mapbox style I've made using the apply functionality. However since this errors shows up during the building during webpack, the website won't work.

Removing import {apply} from 'ol-mapbox-style'; solves the loading, so it's an issue within the package itself.

Environment:
Vue.js + Webpack 3.11.0
image

Problem styling a point feature with "icon-image" via "getStyleFunction"

I am trying to style a point features in an ol.layer.Vector with a simple icon-image defined in a Mapbox GL Style. Therefore I am executing the API function getStyleFunction, which raises an exception:

In line 408 of the index script the function fromTemplate is executed which leads to the mentioned exception. The regex used in this function does not match with the expression in the style property icon-image and returns null (see here ). Which kind of expression is expected here? Has the regex to be adapted or is the style description (see code below) incorrect although it is exported from Mapbox studio?

The style object used looks like this:

{
   "id": "foo",
   "type": "symbol",
   "source": "composite",
   "source-layer": "foolayer",
   "interactive": true,
   "filter": [
     "all",
     [
       "==",
       "$type",
       "Point"
     ],
     [
       "all",
       [
         "==",
         "propertyFoo",
         2
       ]
     ]
   ],
   "layout": {
     "icon-image": "dam-15",
     "visibility": "visible"
   }
}

browser compatiblity

Hello,

I think it would be interesting to add in the documentation a note about browser compatibility.

Can you confirm that using this module it is possible to render full mapbox styles without depending on webgl and therefore support much older browsers than mapbox-gl-js ?

If so I think it is the great strength of this module as it provides an alternative to webgl and server side rendering.

stylefunction.js use ol.js

I saw some code in stylefunction.js which must use ol-debug.js because getFlatMidpoint is not an api function.
image
In ol/geom/LineString
image
If possible i want to use getCoordinateAt(0,5) instead of getFlatMidpoint() because getCoordinateAt is an api function.

Composite of multiple sources

I have a Mapbox style that is a composite of multiple sources: Mapbox Streets V7 + Vector Terrain V2(Composite source). How can I load multiple sources into the ol.source.VectorTile?

I am trying something like this:

var tilegrid = ol.tilegrid.createXYZ({tileSize: 512, maxZoom: 22});
    var layer = new ol.layer.VectorTile({
      source: new ol.source.VectorTile({
        format: new ol.format.MVT(),
        tileGrid: tilegrid,
        tilePixelRatio: 8,
        urls: [
          'http://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v7/{z}/{x}/{y}.vector.pbf?access_token=' + mapboxKey,
          'http://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-terrain-v2/{z}/{x}/{y}.vector.pbf?access_token=' + mapboxKey
          ]
      })
  });

point's fill should use ol.style.Fill

This is a quite interesting bug.

As long as I've used ol-debug.js it worked just fine. However, using a custom build ol.js, it stopped working (does not even render the layer with the basic OL styles), throwing mysterious errors to the console.

I managed to get it up and running again with this patch, but I'd like to hear what you think.

ol.render.Feature does not have geometry.getFlatInteriorPoint

I got an Uncaught TypeError: geometry.getFlatInteriorPoint is not a function unless I define format: new ol.format.MVT({featureClass: ol.Feature}) on ol.source.VectorTile, which suggests that getFlatInteriorPoint is not defined for ol.render.Feature features.

Interestingly your example works just fine without featureClass: ol.Feature.

I'll investigate this issue further, just wanted to mention this at the first place - maybe you have a suggestion from the top of your head.

Vector Style Symbol - Text Rotate

I have a problem related with a label layer which has a field itself that indicates the angle of rotation. I am trying to make it work but I can't.

The example below has the style to represent the rotated labels:

http://jsfiddle.net/8kyp19qz/8/

If I delete the "text-rotate" : "{AA_TXANG}" property labels are displayed with no rotation.

Could someone help me on how I should have to describe the Style configuration?

IE11 vector tile problem

When using IE11 (unfortunately still used in many companies) the code for vector tiles is not working. Even the example crashed with exception "symbol undefined".
Is there a possibility that someone can look at it and fix it if possible?

https://rawgit.com/boundlessgeo/ol-mapbox-style/v2.10.1/example/tilejson-vectortile.html
image

Addtional for older browsers:
Uncaught exception: TypeError: 'inputs[Symbol.iterator]' is not a function

Error thrown at line 1118, column 9 in <anonymous function: module.exports>(output) in http://www.example.com/modules/maps/js/olms.js:
    throw _iteratorError;
called from line 771, column 8 in createFunction(parameters, propertySpec) in http://www.example.com/modules/maps/js/olms.js:
    parameters = extend({}, parameters);
called from line 2018, column 8 in convertToFunctions(properties, type) in http://www.example.com/modules/maps/js/olms.js:
    properties[property] = (0, _function2.default)(value, {
called from line 2072, column 6 in preprocess(layer, fonts) in http://www.example.com/modules/maps/js/olms.js:
    convertToFunctions(layer.paint, 'interpolated');
called from line 1635, column 8 in <anonymous function: exports.default>(olLayer, glStyle, source, resolutions, spriteData, spriteImageUrl, fonts) in http://www.example.com/modules/maps/js/olms.js:
    preprocess(layer, fonts);
called from line 237, column 9 in onChange() in http://www.example.com/modules/maps/js/olms.js:
    style = (0, _mapboxToOlStyle2.default)(layer, glStyle, source, undefined, spriteData, spriteImageUrl, availableFonts);
called from line 225, column 12 in <anonymous function: xhr.onerror>() in http://www.example.com/modules/maps/js/olms.js:
    onChange();

apply() and promises

Hello,

So it looks like the apply() function doesn't return a promise, only the applyStyle() does. Is there a particular reason for this? Is it somehow infeasible? I'd like to know if there's a reason it can't be done before heading down the rabbit hole...

thanks,
fleur

build a version that includes dependencies

When I build the olms.js file using npm install the resulting dist/olms.js file doesn't work in the browser. There's lots of network errors as it tries to download /openlayers/map.js and a load of other missing files.

When [email protected] returns a 404, should fall back to sprites.png

When rendering a mapbox style with a spritesheet on a high-resolution display, if there is no high resolution version on the spritesheet, ol-mapbox-style should fall back to using the regular spritesheet.

Current behavior is to try and read the response as a spritesheet anyways, even if a 404 is returned:

[email protected]:1 GET http://localhost:8080/geoserver/styles/[email protected] 404 ()
olms.js:193 GET http://localhost:8080/geoserver/styles/[email protected] 404 ()
VM4263:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.xhr.onload.xhr.onerror (olms.js:190)

Label handling and Regex functionality for line breaks

I'm not familar with NodeJS so I'll put my proposals here ;-)
Now the code für multi language is usable. But If you have e.g. german, english or similar things with line breaks as "\n", than your OL code will not wrap. Instead it will put a white space for it and the multi line formatting is gone.
Here are my changes to have it like it should.

wrapText (around line 1850 in /dist)

      var textSplit = /\s+/g;
      var words = text.split(textSplit);

fromTemplate (around line 2550 in /dist)

var templateRegEx = /(\s*\S*)\{(.*)\}/g;

String.prototype.matchAll = function(regexp) {
	var matches = [];
	this.replace(regexp, function() {
		var arr = ([]).slice.call(arguments, 0);
		var extras = arr.splice(-2);
		arr.index = extras[0];
		arr.input = extras[1];
		matches.push(arr);
	});
	return matches.length ? matches : null;
}
function fromTemplate(text, properties) {
  var parts = text.matchAll(templateRegEx);
  if (parts) {
	var returnStr = "";
	for (var i in parts) {
		var part = parts[i];
		returnStr += part[1] + (properties[part[2]] || '');
	}
	return returnStr.trim();
  } else {
    return text;
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.