Skip to content

VectorTileLayer

矢量瓦片图层 VectorTileLayer 用于在地图上加载并绘制矢量瓦片数据,并提供了必要的数据交互方法。

VectorTileLayer的样式是在options.style中用JSON数据格式的。 样式定义采用了插件式架构,用户可以在style中用不同过滤条件选取数据,用指定的渲染插件和相应样式来渲染数据。

具体有哪些渲染插件,各插件的样式定义可以参考样式手册。

因为VectorTileLayer的样式属性非常丰富,用户可以采用 MapTalks IDE 软件来用所见即所得的方式来定制VectorTileLayer的样式,然后在程序中加载。

它是 maptalks核心库 TileLayer的子类,同样继承了TileLayer上的方法和配置。

NOTE

参数或配置名称上带 * 表示该参数或配置不能为空,例如下面id后的*号表示参数id是不能为空的:

  • id* String 图层id

样式

矢量瓦片即支持矢量(点线面)的样式,也有把线和面构造为三维线和三维面后,用三维pbr材质渲染的能力。

矢量瓦片整合了feature-filter和function-type来支持数据过滤和动态样式,能方便的把矢量瓦片中的数据分门别类用不同样式和不同级别结合材质魔法渲染出惊人的效果。

因此矢量瓦片很适合大场景下的数据分类渲染,如城市建筑群。比起3dtiles等静态数据,矢量瓦片因为生态更好,样式和数据分离的特点,能在消除数据更新成本的同时,提供3dtiles很难达到的样式设计能力。

矢量瓦片的样式采用了插件式设计,样式由一个个渲染插件来定义的,渲染插件的详细信息可以参考样式手册,以下是一个样式的简单示例:

样式示例
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"
          ]
        ]
      }
    }
  ]
}

构造函数

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

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

参数:

  • id* String 图层id
  • options* Object 配置参数,可选的配置项如下:
配置名类型描述默认值
urlTemplate*Stringurl模板null
fetchOptionsObjectfetch参数null
styleObject图层样式对象null
subdomainsString[]subdomains, 用于替换url模板中的null
tileSizeNumber[]瓦片高宽,单位像素[512, 512]
offsetNumber[]/Function瓦片的偏移量,单位像素,二维数组或函数,函数的参数为 zoom,瓦片的zoom级别,offset(zoom) {}[0, 0]
featuresBoolean瓦片是否返回feature数据true
schemaBoolean瓦片是否返回数据的属性schemafalse
collisionBoolean是否开启点和文字的碰撞检测true
pickingBoolean是否允许图层用identify或identifyAtPoint方法查询数据true
pickingPointBooleanidentify或identifyAtPoint方法的查询结果是否返回查询点的三维空间坐标true
pickingGeometryBooleanidentify或identifyAtPoint方法的查询结果是否包含Geometryfalse
iconErrorUrlStringicon请求失败后的替换图片urlnull
collisionFrameLimitNumber每帧用于计算Collision的时间限制,单位ms1.5
defaultRenderingBoolean是否开启没有style时的默认样式绘制true
textGammaNumber文字的Gamma值,可以用于调整文字清晰度1
maxIconSizeNumber图标最大尺寸限制254
styleScaleNumber图层图标和文字的整体放大系数1
spatialReferenceString / Object图层的空间参考"preset-vt-3857"
tileSystemNumber[]一个四位数数组,用于描述 TileSystem,TileSystem用于定义瓦片的起始坐标和X/Y轴上的编号规律,具体含义参考该链接null
maxAvailableZoomNumber最大可用级别,当地图级别超过maxAvailableZoom后,则显示maxAvailableZoom级别的瓦片。null
repeatWorldBoolean在低级别时,整个世界不满一屏时,是否重复显示世界true
crossOriginString瓦片数据的cross originnull
debugBoolean是否开启调试信息,开启后地图上会绘制瓦片的编号和范围false
maxCacheSizeNumber瓦片缓存的最大数量256
zoomOffsetNumber瓦片zoom级别和地图zoom级别的差值0
errorUrlString瓦片请求失败后的替代链接null
tokenString用于替换url模板中的{token},例如 http://foo/bar/{z}/{x}/{y}?token={token}null
cascadeTilesBoolean是否级联加载低级别瓦片true
enableAltitudeBoolean是否启用要素高程(altitude)true
awareOfTerrainBoolean是否感知地形(贴地形渲染)true
fadeAnimationBoolean是否开启淡入淡出动画false
featureIdPropertyString用作要素id的属性名(feature state用,类似mapbox promoteId)null
altitudePropertyString要素属性中表示高程的字段名"altitude"
tileLimitPerFrameNumber每帧最多处理的瓦片数量1
loadingLimitNumber普通状态下每帧加载瓦片数上限(0为不限)0
glyphSdfLimitPerFrameNumber每帧每瓦片最多绘制的SDF字形数量15
sdfURLStringSDF字体纹理地址null
workerGlyphBoolean是否在worker中处理字形(有urlModifier时自动关闭)true
attributionString图层版权声明null
minZoomNumber图层显示的最小zoomnull
maxZoomNumber图层显示的最大zoomnull
visibleBoolean图层是否隐藏true
opacityNumber图层透明度1
hitDetectBoolean是否开启图层绘制检测(动态鼠标样式),关闭可以提高性能true
collisionScopeString碰撞检测索引的适用范围: map或者layer"layer"

成员方法

setStyle(layerStyle)

设置图层的样式,样式说明请参考该链接。

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

参数:

  • style Object 图层样式对象,可选的属性如下:
属性名类型描述默认值
styleObject[]渲染插件数组[]
featureStyleObject[]单个Feature的渲染插件列表[]
$rootString资源目录根路径null

返回:

  • this
getStyle()

获取图层样式

返回:

  • Object
getComputedStyle()

获取处理后的图层样式,与style的区别主要是:

  • 如果style中定义了$root, computedStyle中的资源路径都是合并后的路径
  • style中的样式定义可能是被压缩后的,computedStyle中都是未压缩的

返回:

  • Object
outlineAll()

高亮图层上所有的数据。

因为高亮是采用后处理实现的,图层需要加入GroupGLLayer,且outline后处理是开启的。

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

返回:

  • this
outlineBatch(idx)

高亮style中序号为idx的渲染插件渲染的数据。

同outlineAll相同,需要加入GroupGLLayer并开启outline后处理。

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

参数:

  • idx Number style的序号

返回:

  • this
outline(idx, featureIds)

序号为idx的渲染插件渲染的数据中,高亮指定的feature。

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

参数:

  • idx Number style的序号
  • featureIds Number[] | String[] feature id 数组

返回:

  • this
cancelOutline()

取消高亮。

返回:

  • this
updateSymbol(idx, symbol)

更新序号为idx的渲染插件的symbol。

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

参数:

  • idx Number 渲染插件序号
  • symbol Object 要更新的symbol属性

返回:

  • this
updateFeatureSymbol(idx, styleIdx, symbol)

更新序号为idx的Feature样式里,序号为styleIdx的渲染插件的symbol。

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

参数:

  • idx Number featureStyle中的Feature样式序号
  • styleIdx Number 样式编号
  • symbol Object 要更新的symbol属性

返回:

  • this
updateSceneConfig(idx, sceneConfig)

更新序号为idx的渲染插件的sceneConfig。

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

参数:

  • idx Number 渲染插件序号
  • sceneConfig Object 要更新的sceneConfig属性

返回:

  • this
updateFeatureSceneConfig(idx, styleIdx, sceneConfig)

更新序号为idx的Feature样式里,序号为styleIdx的渲染插件的sceneConfig。

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

参数:

  • idx Number featureStyle样式序号
  • styleIdx Number 渲染插件编号
  • sceneConfig Object 要更新的sceneConfig属性

返回:

  • this
updateDataConfig(idx, dataConfig)

更新序号为idx的渲染插件的dataConfig。

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

参数:

  • idx Number 渲染插件序号
  • dataConfig Object 要更新的dataConfig属性

返回:

  • this
updateFeatureDataConfig(idx, styleIdx, dataConfig)

更新序号为idx的Feature样式里,序号为styleIdx的渲染插件的dataConfig。

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

参数:

  • idx Number featureStyle样式序号
  • styleIdx Number 渲染插件编号
  • dataConfig Object 要更新的dataConfig属性

返回:

  • this
identify(coordinates, options)

在图层上查询给定坐标处的数据。 需要注意的是,只有绘制出来的数据才能被查询到。

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

参数:

  • coordinates Number[] 坐标值
  • options Object 设置,可能的属性: | 属性名 | 类型 | 描述 | 默认值 | | ------ | :----: | ---- | :-----------: | | tolerance | Number | 查询时的像素冗余值 | 3 |

返回:

  • Object[]
identifyAtPoint(containerPoint, options)

在图层上查询给定屏幕坐标处的数据

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

参数:

  • coordinates Number[] 坐标值
  • options Object 设置,可能的属性:
属性名类型描述默认值
toleranceNumber查询时的像素冗余值3

返回:

  • Object[]
getDataSchema(zoom)

获取给定级别上的图层定义和属性定义。

需要注意的是,只有某个级别的瓦片的曾经载入过,才能正常获取,未载入过的瓦片级别的data schema是无法获取的。

js
const schema = layer.getDataSchema(8);

参数:

  • zoom Number 瓦片级别

返回:

  • Object[]
getCurrentRenderedFeatures()

获取当前屏幕中已渲染的要素(坐标会转换为GeoJSON格式)。

返回:

  • Object[]
getRenderedFeatures()

获取已渲染的所有要素。

返回:

  • Object[]
getRenderedFeaturesAsync(options)

异步分页获取已渲染的要素。

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

参数:

  • options Object 设置,可能的属性: | 属性名 | 类型 | 描述 | 默认值 | | ------ | :----: | ---- | :-----------: | | countPerTime | Number | 每次分页获取的要素数量上限 | 10000 |

返回:

  • Promise
highlight(highlights)

高亮指定要素。highlights支持 { id }{ filter, name } 两种形式(filter形式需要开启 options.features)。

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

参数:

  • highlights Object 高亮配置,可能的属性: | 属性名 | 类型 | 描述 | | ------ | :----: | ---- | | id | String | Number | 要素id | | filter | Object | 要素过滤器 | | name | String | 高亮样式名称 |

返回:

  • this
cancelHighlight(ids)

取消指定要素的高亮。

参数:

  • ids Number[] | String[] 要素id数组

返回:

  • this
cancelAllHighlight()

取消所有要素的高亮。

返回:

  • this
outlineFeatures(featureIds)

高亮指定id的要素(outline系列方法之一,需要加入 GroupGLLayer 并开启 outline 后处理)。

参数:

  • featureIds Number[] | String[] 要素id数组

返回:

  • this
setFeatureState(source, state)

设置要素的状态(feature state)。

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

参数:

  • source Object 要素来源,{ id, layer }
  • state Object 要设置的要素状态

返回:

  • this
getFeatureState(source)

获取要素的状态。

参数:

  • source Object 要素来源,{ id, layer }

返回:

  • Object
removeFeatureState(source, key)

移除要素状态中的指定属性。

参数:

  • source Object 要素来源,{ id, layer }
  • key String 要移除的状态属性名

返回:

  • this
validateStyle()

校验style的合法性(filter必须为default/true/数组/带condition的对象)。

返回:

  • Boolean
forceReload()

强制重载瓦片,同时会使worker内的瓦片缓存失效。

返回:

  • this
setURLModifier(modifier)

设置瓦片URL处理函数。

参数:

  • modifier Function URL处理函数

返回:

  • this
getURLModifier()

获取瓦片URL处理函数。

返回:

  • Function
getGroundConfig()

获取图层背景(background)配置,供GroupGLLayer的地面渲染使用。

返回:

  • Object
isDefaultRender()

是否处于无style时的默认绘制状态。

返回:

  • Boolean
clearData()

清除瓦片数据。

继承自TileLayer的方法

具体可以参考父类TileLayer的API文档

getTileSize()

获取瓦片高宽

返回:

  • Size
getTiles()

获取瓦片

返回:

  • Object
getTileUrl(x, y, z)

获取瓦片url

返回:

  • String
clear()

清空图层

toJSON()

获得图层的JSON对象,这个JSON对象可以通过 maptalks.Layer.fromJSDN(json) 方法还原为图层对象。

返回:

  • Object
getSpatialReference()

获得图层的空间参考对象。

返回:

  • SpatialReference

继承自Layer的方法

具体可以参考父类Layer的API文档

getId()

获得图层id

返回:

  • Number | String
setId(id)

设置图层id

返回:

  • this
addTo(map)

添加到地图上。

返回:

  • this
getMinZoom()

获取最小瓦片级别。

返回:

  • Number
getMaxZoom()

获取最大瓦片级别。

返回:

  • Number
getMap()

获取图层添加到的map对象。

返回:

  • Map
getProjection()

获取图层的projection。

返回:

  • Projection
show()

隐藏图层。

返回:

  • this
hide()

隐藏图层。

返回:

  • this
isVisible()

判定图层是否显示。

返回:

  • Boolean
remove()

删除图层。

返回:

  • this
on(events, handler, context)

注册图层的监听事件

返回:

  • this
addEventListener(events, handler, context)

同 on 方法

返回:

  • this
once(events, handler, context)

注册图层的监听事件,响应后即删除

返回:

  • this
off(events, handler, context)

移除图层注册的监听事件

返回:

  • this
removeEventListener(events, handler, context)

同 off 方法

返回:

  • this
listens(events, handler, context)

判断图层是否监听了events事件。

返回:

  • Boolean
fire(event, params)

手动发射一个事件,params是时间参数。

返回:

  • this
setOptions(options)

设置图层配置。

返回:

  • this
config(key, value)

更新某个图层配置。

返回:

  • this

静态方法

compressStyleJSON(style)

通过合并相同定义的渲染插件,把style JSON压缩为尺寸更小的JSON对象。

js
const compressedStyle = VectorTileLayer.compressStyleJSON(style);

参数:

  • style Object 样式对象

返回:

  • Object
registerPlugin(Plugin)

注册新的渲染插件。

js
VectorTileLayer.registerPlugin(PluginClazz);

参数:

  • PluginClazz PainterPlugin 要注册的渲染插件类
getPlugins()

获取所有注册的渲染插件。

js
const pluginClasses = VectorTileLayer.getPlugins();

返回:

  • PainterPlugin[]
fromJSON(json)

从图层的json对象创建一个VectorTileLayer对象。

js
const json = layer.toJSON();

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

返回:

  • VectorTileLayer
loadFrom(url, fetchOptions)

从样式JSON文件加载并创建图层实例(异步)。

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

参数:

  • url String 样式JSON文件的地址
  • fetchOptions Object 可选的fetch配置

返回:

  • Promise<VectorTileLayer>

事件

图层事件监听示例代码:

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

图层事件

iblupdated

环境光更新事件。

参数属性:

属性名类型
typeString"iblupdated"
targetVectorTileLayerthis
canvasisdirty

图层画布产生绘制的事件。

参数属性:

属性名类型
typeString"canvasisdirty"
targetVectorTileLayerthis
workerready

worker准备就绪事件。

参数属性:

属性名类型
typeString"workerready"
targetVectorTileLayerthis
datareceived

获取到瓦片数据事件。

参数属性:

属性名类型
typeString"datareceived"
targetVectorTileLayerthis
urlString瓦片数据地址
pluginsinited

渲染插件初始化结束事件。

参数属性:

属性名类型
typeString"pluginsinited"
targetVectorTileLayerthis
setstyle

设置样式事件。

参数属性:

属性名类型
typeString"setstyle"
targetVectorTileLayerthis
styleObject[]样式对象
computedStyleObject[]处理后的样式对象
updatesceneconfig

updatesceneconfig事件。

参数属性:

属性名类型
typeString"updatesceneconfig"
targetVectorTileLayerthis
indexNumber样式序号
sceneConfigObjectscene config对象
updatefeaturesceneconfig

updatefeaturesceneconfig事件。

参数属性:

属性名类型
typeString"updatefeaturesceneconfig"
targetVectorTileLayerthis
indexNumberFeature样式序号
styleIdxNumberFeature渲染插件序号
sceneConfigObjectscene config对象
updatedataconfig

updatedataconfig事件。

参数属性:

属性名类型
typeString"updatedataconfig"
targetVectorTileLayerthis
indexNumber样式序号
dataConfigObjectdata config对象
updatefeaturedataconfig

updatefeaturedataconfig事件。

参数属性:

属性名类型
typeString"updatefeaturedataconfig"
targetVectorTileLayerthis
indexNumberFeature样式序号
styleIdxNumberFeature渲染插件序号
dataConfigObjectdata config对象
updatesymbol

updatesymbol事件。

参数属性:

属性名类型
typeString"updatesymbol"
targetVectorTileLayerthis
indexNumber样式序号
symbolObjectsymbol对象
updatefeaturesymbol

updatefeaturesymbol事件。

参数属性:

属性名类型
typeString"updatefeaturesymbol"
targetVectorTileLayerthis
indexNumberFeature样式序号
featureStyleIndexNumberFeature渲染插件序号
symbolObjectsymbol对象
cleardata

渲染器清除瓦片数据时触发的事件。

参数属性:

属性名类型
typeString"cleardata"
targetVectorTileLayerthis
refreshstyle

样式刷新事件。

参数属性:

属性名类型
typeString"refreshstyle"
targetVectorTileLayerthis
contextcreate

GL上下文创建事件。

参数属性:

属性名类型
typeString"contextcreate"
targetVectorTileLayerthis
reglObjectregl实例
deviceObjectGPU设备(WebGPU模式)

继承自TileLayer的事件

tileload

瓦片载入事件。

参数属性:

属性名类型
typeString"tileload"
targetVectorTileLayerthis
tileObject瓦片对象
tileImageObject瓦片数据
tileerror

瓦片载入错误事件。

参数属性:

属性名类型
typeString"tileerror"
targetVectorTileLayerthis
errorString错误信息
tileObject瓦片对象

继承自Layer的事件

clear

图层被清除事件。

参数属性:

属性名类型
typeString"clear"
targetVectorTileLayerthis
idchange

图层id变化事件。

参数属性:

属性名类型
typeString"idchange"
targetVectorTileLayerthis
oldString旧的id
newString新的id
renderercreate

renderer创建事件

参数属性:

属性名类型
typeString"renderercreate"
targetVectorTileLayerthis
rendererVectorTileLayerRenderer
canvascreate

canvas创建事件

参数属性:

属性名类型
typeString"canvascreate"
targetVectorTileLayerthis
glWebGLRenderingContext2D
renderstart

开始渲染事件。

参数属性:

属性名类型
typeString"renderstart"
targetVectorTileLayerthis
renderend

结束渲染事件。

参数属性:

属性名类型
typeString"renderend"
targetVectorTileLayerthis

本文档已与 @maptalks/gl-layers 2026 源码核对(api-notes-vt-gl.md)