Skip to content

VectorTileLayer

VectorTileLayer is a vector tile layer used to load and render vector tile data on the map, and provides the necessary methods for data interaction.

The style of VectorTileLayer is defined in options.style in JSON format. The style definition adopts a plugin-based architecture: in the style, you can select data with different filter conditions and render it with the specified render plugin and its corresponding style.

For the available render plugins and the style definition of each plugin, refer to the style manual.

Because VectorTileLayer has a rich set of style properties, you can use the MapTalks IDE to customize the style of VectorTileLayer in a WYSIWYG way, and then load it in your program.

It is a subclass of TileLayer of the core maptalks library, inheriting the methods and options of TileLayer.

NOTE

A * on a parameter or option name means the parameter or option is required. For example, the * after id below means the parameter id is required:

  • id* String the layer id

Style

Vector tiles support styles for vector features (points, lines and polygons), and also have the ability to build lines and polygons into 3D lines and 3D faces and render them with 3D PBR materials.

Vector tiles integrate feature-filter and function-type to support data filtering and dynamic styling, making it easy to categorize the data in vector tiles and render them with different styles, levels and material magic for stunning effects.

Vector tiles are therefore well suited to categorized data rendering in large scenes, such as city building clusters. Compared with static data like 3dtiles, vector tiles benefit from a better ecosystem and the separation of style and data, which eliminates data update costs while providing styling capabilities that are hard to achieve with 3dtiles.

The vector tile style adopts a plugin-based design: styles are defined by render plugins. For the details of the render plugins, refer to the style manual. Here is a simple style example:

Style Example
json
{
  "style": [
    {
      "renderPlugin": {
        "type": "fill",
        "dataConfig": {
          "type": "fill",
          "only2D": true
        },
        "sceneConfig": {
          "depthFunc": "always",
          "blendSrc": "one"
        }
      },
      "symbol": {
        "visible": true,
        "polygonFill": "rgba(0,0,0,1)",
        "polygonOpacity": 1
      },
      "filter": {
        "title": "desert",
        "value": [
          "all",
          [
            "==",
            "$layer",
            "desert"
          ],
          [
            "==",
            "$type",
            "Polygon"
          ]
        ]
      }
    },
    {
      "renderPlugin": {
        "type": "line",
        "dataConfig": {
          "type": "line",
          "only2D": true
        },
        "sceneConfig": {
          "blendSrc": "one"
        }
      },
      "symbol": {
        "visible": true,
        "lineOpacity": 1,
        "lineWidth": 1,
        "lineColor": "rgba(0,0,0,1)",
        "lineJoin": "miter",
        "lineCap": "butt",
        "lineDx": 0,
        "lineDy": 0,
        "lineDasharray": [
          0,
          0,
          0,
          0
        ],
        "lineDashColor": "rgba(0,0,0,1)",
        "lineStrokeWidth": 0,
        "lineStrokeColor": "rgba(0,0,0,1)"
      },
      "detail": {
        "layer": "desert-outline",
        "enable": {
          "lineWidth": false,
          "lineColor": false,
          "lineStrokeWidth": false,
          "lineStrokeColor": false
        }
      },
      "filter": {
        "title": "desert-outline",
        "value": [
          "all",
          [
            "==",
            "$layer",
            "desert"
          ],
          [
            "==",
            "$type",
            "Polygon"
          ]
        ]
      }
    }
  ]
}

Constructor

js
import { VectorTileLayer } from '@maptalks/gl-layers';

new VectorTileLayer('vt0', {
  urlTemplate: 'https://tiles.maptalks.com/test/{z}/{x}/{y}.mvt'
});
Details

Parameters:

  • id* String the layer id
  • options* Object options, the available options are as follows:
OptionTypeDescriptionDefault
urlTemplate*StringURL templatenull
fetchOptionsObjectfetch optionsnull
styleObjectThe style object of the layernull
subdomainsString[]subdomains, used to replace {s} in the URL templatenull
tileSizeNumber[]The tile width and height, in pixels[512, 512]
offsetNumber[]/FunctionThe tile offset in pixels. A two-element array or a function; the function takes zoom (the tile zoom level) as its argument, offset(zoom) {}[0, 0]
featuresBooleanWhether tiles return feature datatrue
schemaBooleanWhether tiles return the attribute schema of the datafalse
collisionBooleanWhether to enable collision detection for points and texttrue
pickingBooleanWhether the layer is allowed to query data with the identify or identifyAtPoint methodstrue
pickingPointBooleanWhether the query results of identify or identifyAtPoint include the 3D spatial coordinates of the query pointtrue
pickingGeometryBooleanWhether the query results of identify or identifyAtPoint include Geometryfalse
iconErrorUrlStringThe fallback image URL for failed icon requestsnull
collisionFrameLimitNumberThe time limit for collision computation per frame, in ms1.5
defaultRenderingBooleanWhether to enable default style rendering when there is no styletrue
textGammaNumberThe gamma value of text, which can be used to adjust text sharpness1
maxIconSizeNumberThe maximum icon size limit254
styleScaleNumberThe overall scale factor of the layer's icons and text1
spatialReferenceString / ObjectThe spatial reference of the layer"preset-vt-3857"
tileSystemNumber[]A four-element array describing the TileSystem. The TileSystem defines the origin coordinate of tiles and the numbering rule on the X/Y axes. See this link for detailsnull
maxAvailableZoomNumberThe maximum available zoom level. When the map zoom level exceeds maxAvailableZoom, tiles of the maxAvailableZoom level are displayed.null
repeatWorldBooleanWhether to repeat the world when the whole world does not fill the screen at low zoom levelstrue
crossOriginStringThe cross origin setting of the tile datanull
debugBooleanWhether to enable debug info; when enabled, tile indices and extents are drawn on the mapfalse
maxCacheSizeNumberThe maximum number of cached tiles256
zoomOffsetNumberThe offset between the tile zoom level and the map zoom level0
errorUrlStringThe fallback URL for failed tile requestsnull
tokenStringUsed to replace {token} in the URL template, e.g. http://foo/bar/{z}/{x}/{y}?token={token}null

|cascadeTiles | Boolean | Whether to cascade-load tiles of lower zoom levels | true | |enableAltitude | Boolean | Whether to enable feature altitude | true | |awareOfTerrain | Boolean | Whether to be aware of terrain (render draped on the terrain) | true | |fadeAnimation | Boolean | Whether to enable fade in/out animation | false | |featureIdProperty| String | The property name used as the feature id (for feature state, similar to mapbox's promoteId) | null | |altitudeProperty | String | The property name in feature attributes that represents altitude | "altitude" | |tileLimitPerFrame| Number | The maximum number of tiles processed per frame | 1 | |loadingLimit | Number | The maximum number of tiles loaded per frame in normal state (0 means unlimited) | 0 | |glyphSdfLimitPerFrame | Number | The maximum number of SDF glyphs drawn per tile per frame | 15 | |sdfURL | String | The URL of the SDF font texture | null | |workerGlyph | Boolean | Whether to process glyphs in the worker (automatically disabled when a urlModifier is set) | true | |attribution | String | The attribution of the layer | null | |minZoom | Number | The minimum zoom level at which the layer is displayed | null | |maxZoom | Number | The maximum zoom level at which the layer is displayed | null | |visible | Boolean | Whether the layer is visible | true | |opacity | Number | The opacity of the layer | 1 | |hitDetect | Boolean | Whether to enable layer drawing detection (dynamic mouse cursor styles); disabling it can improve performance | true | |collisionScope | String | The scope of the collision detection index: "map" or "layer" | "layer" |

Methods

setStyle(layerStyle)

Sets the style of the layer. See this link for the style documentation.

js
const style = {
  style: [
    {
      filter : true,            // 数据的过滤条件
      renderPlugin: {           // 渲染插件
        type : 'native-point',
        dataConfig : {
          type : 'native-point'
        }
      },
      symbol: {                 // 样式定义
        markerSize: 6,
        markerType: 'circle',
        markerFill: '#0f0'
      }
    }
  ]
};
layer.setStyle(style);

Parameters:

  • style Object the layer style object, with the following optional properties:
PropertyTypeDescriptionDefault
styleObject[]The render plugin array[]
featureStyleObject[]The render plugin list of a single feature[]
$rootStringThe root path of the resource directorynull

Returns:

  • this
getStyle()

Gets the layer style.

Returns:

  • Object
getComputedStyle()

Gets the processed layer style. The main differences from style are:

  • If $root is defined in the style, all resource paths in computedStyle are the merged paths
  • The style definitions in style may be compressed, while those in computedStyle are uncompressed

Returns:

  • Object
outlineAll()

Highlights all data on the layer.

Because highlighting is implemented with post-processing, the layer must be added to a GroupGLLayer with the outline post-processing enabled.

js
layer.addTo(groupGLLayer);
layer.outlineAll();

Returns:

  • this
outlineBatch(idx)

Highlights the data rendered by the render plugin with index idx in the style.

Same as outlineAll: the layer must be added to a GroupGLLayer with the outline post-processing enabled.

js
layer.addTo(groupGLLayer);
layer.outlineBatch(0);

Parameters:

  • idx Number the index in the style

Returns:

  • this
outline(idx, featureIds)

Highlights the specified features among the data rendered by the render plugin with index idx.

js
layer.addTo(groupGLLayer);
layer.outline(0, [0]);

Parameters:

  • idx Number the index in the style
  • featureIds Number[] | String[] an array of feature ids

Returns:

  • this
cancelOutline()

Cancels the highlight.

Returns:

  • this
updateSymbol(idx, symbol)

Updates the symbol of the render plugin with index idx.

js
layer.updateSymbol(0, { polygonFill: '#0f0' });

Parameters:

  • idx Number the render plugin index
  • symbol Object the symbol properties to update

Returns:

  • this
updateFeatureSymbol(idx, styleIdx, symbol)

Updates the symbol of the render plugin with index styleIdx in the feature style with index idx.

js
const style = {
  featureStyle: [
    {
      id: 16,
      style: [
        {
          renderPlugin: {
            dataConfig: {
              type: 'fill'
            },
            sceneConfig: {
              antialias: false
            },
            type: 'fill'
          },
          symbol: {
            polygonFill: '#f00'
          }
        }
      ]
    }
  ]
}
layer.updateFeatureSymbol(0, 0, { polygonFill: '#0f0' });

Parameters:

  • idx Number the index of the feature style in featureStyle
  • styleIdx Number the style index
  • symbol Object the symbol properties to update

Returns:

  • this
updateSceneConfig(idx, sceneConfig)

Updates the sceneConfig of the render plugin with index idx.

js
layer.updateSceneConfig(0, { collision: false });

Parameters:

  • idx Number the render plugin index
  • sceneConfig Object the sceneConfig properties to update

Returns:

  • this
updateFeatureSceneConfig(idx, styleIdx, sceneConfig)

Updates the sceneConfig of the render plugin with index styleIdx in the feature style with index idx.

js
const style = {
  featureStyle: [
    {
      id: 16,
      style: [
        {
          renderPlugin: {
            dataConfig: {
              type: 'fill'
            },
            sceneConfig: {
              antialias: false
            },
            type: 'fill'
          },
          symbol: {
            polygonFill: '#f00'
          }
        }
      ]
    }
  ]
}
layer.updateFeatureSceneConfig(0, 0, { antialias: true });

Parameters:

  • idx Number the index of the feature style in featureStyle
  • styleIdx Number the render plugin index
  • sceneConfig Object the sceneConfig properties to update

Returns:

  • this
updateDataConfig(idx, dataConfig)

Updates the dataConfig of the render plugin with index idx.

js
layer.updateDataConfig(0, { altitudeProperty: 'height' });

Parameters:

  • idx Number the render plugin index
  • dataConfig Object the dataConfig properties to update

Returns:

  • this
updateFeatureDataConfig(idx, styleIdx, dataConfig)

Updates the dataConfig of the render plugin with index styleIdx in the feature style with index idx.

js
const style = {
  featureStyle: [
    {
      id: 16,
      style: [
        {
          renderPlugin: {
            dataConfig: {
              type: 'fill'
            },
            sceneConfig: {
              antialias: false
            },
            type: 'fill'
          },
          symbol: {
            polygonFill: '#f00'
          }
        }
      ]
    }
  ]
}
layer.updateFeatureDataConfig(0, 0, { foo: 1 });

Parameters:

  • idx Number the index of the feature style in featureStyle
  • styleIdx Number the render plugin index
  • dataConfig Object the dataConfig properties to update

Returns:

  • this
identify(coordinates, options)

Queries data at the given coordinate on the layer. Note that only rendered data can be queried.

js
layer.identify([121.23, 39.34], { tolerance: 2 })

Parameters:

  • coordinates Number[] the coordinate value
  • options Object options, the possible properties are: | Property | Type | Description | Default | | ------ | :----: | ---- | :-----------: | | tolerance | Number | The pixel tolerance for the query | 3 |

Returns:

  • Object[]
identifyAtPoint(containerPoint, options)

Queries data at the given container point on the layer.

js
layer.identifyAtPoint([400, 300], { tolerance: 2 })

Parameters:

  • coordinates Number[] the coordinate value
  • options Object options, the possible properties are:
PropertyTypeDescriptionDefault
toleranceNumberThe pixel tolerance for the query3

Returns:

  • Object[]
getDataSchema(zoom)

Gets the layer definition and property definition at the given zoom level.

Note that the schema of a zoom level can only be fetched after tiles of that level have been loaded; the data schema of a zoom level whose tiles have never been loaded cannot be fetched.

js
const schema = layer.getDataSchema(8);

Parameters:

  • zoom Number the tile zoom level

Returns:

  • Object[]
getCurrentRenderedFeatures()

Gets the features currently rendered on screen (coordinates are converted to GeoJSON format).

Returns:

  • Object[]
getRenderedFeatures()

Gets all rendered features.

Returns:

  • Object[]
getRenderedFeaturesAsync(options)

Asynchronously fetches the rendered features in pages.

js
const features = await layer.getRenderedFeaturesAsync({ countPerTime: 10000 });

Parameters:

  • options Object options, the possible properties are: | Property | Type | Description | Default | | ------ | :----: | ---- | :-----------: | | countPerTime | Number | The maximum number of features fetched per page | 10000 |

Returns:

  • Promise
highlight(highlights)

Highlights the specified features. highlights supports either { id } or { filter, name } (the filter form requires options.features to be enabled).

js
layer.highlight({ id: 'feature-1' });

Parameters:

  • highlights Object highlight options, the possible properties are: | Property | Type | Description | | ------ | :----: | ---- | | id | String | Number | the feature id | | filter | Object | the feature filter | | name | String | the highlight style name |

Returns:

  • this
cancelHighlight(ids)

Cancels the highlight of the specified features.

Parameters:

  • ids Number[] | String[] an array of feature ids

Returns:

  • this
cancelAllHighlight()

Cancels the highlight of all features.

Returns:

  • this
outlineFeatures(featureIds)

Highlights the features with the specified ids (one of the outline series of methods; the layer must be added to a GroupGLLayer with the outline post-processing enabled).

Parameters:

  • featureIds Number[] | String[] an array of feature ids

Returns:

  • this
setFeatureState(source, state)

Sets the state of a feature (feature state).

js
layer.setFeatureState({ id: 'feature-1', layer: 'layer-name' }, { hot: true });

Parameters:

  • source Object the feature source, { id, layer }
  • state Object the feature state to set

Returns:

  • this
getFeatureState(source)

Gets the state of a feature.

Parameters:

  • source Object the feature source, { id, layer }

Returns:

  • Object
removeFeatureState(source, key)

Removes the specified property from the feature state.

Parameters:

  • source Object the feature source, { id, layer }
  • key String the name of the state property to remove

Returns:

  • this
validateStyle()

Validates the style (the filter must be 'default', true, an array, or an object with a condition).

Returns:

  • Boolean
forceReload()

Forcibly reloads tiles and invalidates the tile cache in the worker.

Returns:

  • this
setURLModifier(modifier)

Sets the tile URL processing function.

Parameters:

  • modifier Function the URL processing function

Returns:

  • this
getURLModifier()

Gets the tile URL processing function.

Returns:

  • Function
getGroundConfig()

Gets the layer background config, used for the ground rendering of the GroupGLLayer.

Returns:

  • Object
isDefaultRender()

Whether the layer is in the default rendering state without a style.

Returns:

  • Boolean
clearData()

Clears the tile data.

Methods Inherited from TileLayer

See the API documentation of the parent class TileLayer for details.

getTileSize()

Gets the tile width and height.

Returns:

  • Size
getTiles()

Gets the tiles.

Returns:

  • Object
getTileUrl(x, y, z)

Gets the tile URL.

Returns:

  • String
clear()

Clears the layer.

toJSON()

Gets the JSON object of the layer, which can be restored to a layer object with the maptalks.Layer.fromJSON(json) method.

Returns:

  • Object
getSpatialReference()

Gets the spatial reference of the layer.

Returns:

  • SpatialReference

Methods Inherited from Layer

See the API documentation of the parent class Layer for details.

getId()

Gets the layer id.

Returns:

  • Number | String
setId(id)

Sets the layer id.

Returns:

  • this
addTo(map)

Adds the layer to the map.

Returns:

  • this
getMinZoom()

Gets the minimum zoom level.

Returns:

  • Number
getMaxZoom()

Gets the maximum zoom level.

Returns:

  • Number
getMap()

Gets the map object that the layer is added to.

Returns:

  • Map
getProjection()

Gets the projection of the layer.

Returns:

  • Projection
show()

Shows the layer.

Returns:

  • this
hide()

Hides the layer.

Returns:

  • this
isVisible()

Checks whether the layer is visible.

Returns:

  • Boolean
remove()

Removes the layer.

Returns:

  • this
on(events, handler, context)

Registers an event listener on the layer.

Returns:

  • this
addEventListener(events, handler, context)

Same as the on method.

Returns:

  • this
once(events, handler, context)

Registers a one-time event listener on the layer; it is removed after being fired.

Returns:

  • this
off(events, handler, context)

Removes the registered event listener from the layer.

Returns:

  • this
removeEventListener(events, handler, context)

Same as the off method.

Returns:

  • this
listens(events, handler, context)

Checks whether the layer is listening to the given events.

Returns:

  • Boolean
fire(event, params)

Manually fires an event; params is the event parameter.

Returns:

  • this
setOptions(options)

Sets the layer options.

Returns:

  • this
config(key, value)

Updates a layer option.

Returns:

  • this

Static Methods

compressStyleJSON(style)

Compresses the style JSON into a smaller JSON object by merging render plugins with identical definitions.

js
const compressedStyle = VectorTileLayer.compressStyleJSON(style);

Parameters:

  • style Object the style object

Returns:

  • Object
registerPlugin(Plugin)

Registers a new render plugin.

js
VectorTileLayer.registerPlugin(PluginClazz);

Parameters:

  • PluginClazz PainterPlugin the render plugin class to register
getPlugins()

Gets all registered render plugins.

js
const pluginClasses = VectorTileLayer.getPlugins();

Returns:

  • PainterPlugin[]
fromJSON(json)

Creates a VectorTileLayer object from the layer's JSON object.

js
const json = layer.toJSON();

const layerCopied = maptalks.Layer.fromJSON(json);

Returns:

  • VectorTileLayer
loadFrom(url, fetchOptions)

Loads a style JSON file and creates a layer instance from it (asynchronous).

js
const layer = await VectorTileLayer.loadFrom(url, {});

Parameters:

  • url String the URL of the style JSON file
  • fetchOptions Object optional fetch options

Returns:

  • Promise<VectorTileLayer>

Events

Example code for listening to layer events:

js
// 监听workerready事件
layer.once('workerready', e => {
  // e为事件参数
  console.log('worker is ready');
});

// 监听tileload事件
layer.on('tileload', e => {
  // e为事件参数
  console.log('loaded a tile', e.tile);
});

Layer Events

iblupdated

Fired when the ambient light is updated.

Properties:

PropertyTypeValue
typeString"iblupdated"
targetVectorTileLayerthis
canvasisdirty

Fired when the layer canvas is redrawn.

Properties:

PropertyTypeValue
typeString"canvasisdirty"
targetVectorTileLayerthis
workerready

Fired when the worker is ready.

Properties:

PropertyTypeValue
typeString"workerready"
targetVectorTileLayerthis
datareceived

Fired when tile data is received.

Properties:

PropertyTypeValue
typeString"datareceived"
targetVectorTileLayerthis
urlStringthe URL of the tile data
pluginsinited

Fired when the render plugins finish initialization.

Properties:

PropertyTypeValue
typeString"pluginsinited"
targetVectorTileLayerthis
setstyle

Fired when the style is set.

Properties:

PropertyTypeValue
typeString"setstyle"
targetVectorTileLayerthis
styleObject[]the style object
computedStyleObject[]the processed style object
updatesceneconfig

Fired on updatesceneconfig.

Properties:

PropertyTypeValue
typeString"updatesceneconfig"
targetVectorTileLayerthis
indexNumberthe style index
sceneConfigObjectthe sceneConfig object
updatefeaturesceneconfig

Fired on updatefeaturesceneconfig.

Properties:

PropertyTypeValue
typeString"updatefeaturesceneconfig"
targetVectorTileLayerthis
indexNumberthe feature style index
styleIdxNumberthe feature render plugin index
sceneConfigObjectthe sceneConfig object
updatedataconfig

Fired on updatedataconfig.

Properties:

PropertyTypeValue
typeString"updatedataconfig"
targetVectorTileLayerthis
indexNumberthe style index
dataConfigObjectthe dataConfig object
updatefeaturedataconfig

Fired on updatefeaturedataconfig.

Properties:

PropertyTypeValue
typeString"updatefeaturedataconfig"
targetVectorTileLayerthis
indexNumberthe feature style index
styleIdxNumberthe feature render plugin index
dataConfigObjectthe dataConfig object
updatesymbol

Fired on updatesymbol.

Properties:

PropertyTypeValue
typeString"updatesymbol"
targetVectorTileLayerthis
indexNumberthe style index
symbolObjectthe symbol object
updatefeaturesymbol

Fired on updatefeaturesymbol.

Properties:

PropertyTypeValue
typeString"updatefeaturesymbol"
targetVectorTileLayerthis
indexNumberthe feature style index
featureStyleIndexNumberthe feature render plugin index
symbolObjectthe symbol object
cleardata

Fired when the renderer clears the tile data.

Properties:

PropertyTypeValue
typeString"cleardata"
targetVectorTileLayerthis
refreshstyle

Fired when the style is refreshed.

Properties:

PropertyTypeValue
typeString"refreshstyle"
targetVectorTileLayerthis
contextcreate

Fired when the GL context is created.

Properties:

PropertyTypeValue
typeString"contextcreate"
targetVectorTileLayerthis
reglObjectthe regl instance
deviceObjectthe GPU device (WebGPU mode)

Events Inherited from TileLayer

tileload

Fired when a tile is loaded.

Properties:

PropertyTypeValue
typeString"tileload"
targetVectorTileLayerthis
tileObjectthe tile object
tileImageObjectthe tile image data
tileerror

Fired when a tile fails to load.

Properties:

PropertyTypeValue
typeString"tileerror"
targetVectorTileLayerthis
errorStringthe error message
tileObjectthe tile object

Events Inherited from Layer

clear

Fired when the layer is cleared.

Properties:

PropertyTypeValue
typeString"clear"
targetVectorTileLayerthis
idchange

Fired when the layer id changes.

Properties:

PropertyTypeValue
typeString"idchange"
targetVectorTileLayerthis
oldStringthe old id
newStringthe new id
renderercreate

Fired when the renderer is created.

Properties:

PropertyTypeValue
typeString"renderercreate"
targetVectorTileLayerthis
rendererVectorTileLayerRenderer
canvascreate

Fired when the canvas is created.

Properties:

PropertyTypeValue
typeString"canvascreate"
targetVectorTileLayerthis
glWebGLRenderingContext2D
renderstart

Fired when rendering starts.

Properties:

PropertyTypeValue
typeString"renderstart"
targetVectorTileLayerthis
renderend

Fired when rendering ends.

Properties:

PropertyTypeValue
typeString"renderend"
targetVectorTileLayerthis

This document has been cross-checked against the @maptalks/gl-layers 2026 source code (api-notes-vt-gl.md)