TransformStyleFunction()
TransformStyleFunction = (
previous
:StyleSpecification
|undefined
,next
:StyleSpecification
) =>StyleSpecification
定义于: src/style/style.ts:173
作为Map#setStyle选项的一部分,transformStyle是一个便捷函数,允许在样式被获取后但在提交到地图状态之前对其进行修改;
此函数暴露了前一个和下一个样式,可用于支持各种功能,例如:
- 当前一个样式携带某些需要优雅地传递到新样式的"状态"时;
- 当所需的样式是前一个样式和传入样式的特定组合时;
- 当传入的样式需要根据外部状态进行修改时;
- 当传入的样式使用相对路径时,需要将其转换为绝对路径;
参数
参数 | 类型 | 描述 |
---|---|---|
previous | StyleSpecification | undefined | 当前样式 |
next | StyleSpecification | 下一个样式 |
返回值
StyleSpecification
将应用于地图的结果样式
示例
map.setStyle('https://demotiles.maplibre.org/style.json', {
transformStyle: (previousStyle, nextStyle) => ({
...nextStyle,
// 将相对精灵路径(如"../sprite")转为绝对路径
sprite: new URL(nextStyle.sprite, "https://demotiles.maplibre.org/styles/osm-bright-gl-style/sprites/").href,
// 将相对字体路径(如"../fonts/{fontstack}/{range}.pbf")转为绝对路径
glyphs: new URL(nextStyle.glyphs, "https://demotiles.maplibre.org/font/").href,
sources: {
// 将相对矢量URL(如"../../")转为绝对路径
...nextStyle.sources.map(source => {
if (source.url) {
source.url = new URL(source.url, "https://api.maptiler.com/tiles/osm-bright-gl-style/");
}
return source;
}),
// 从前一个样式复制源
'osm': previousStyle.sources.osm
},
layers: [
// 背景图层
nextStyle.layers[0],
// 从前一个样式复制图层
previousStyle.layers[0],
// 来自下一个样式的其他图层
...nextStyle.layers.slice(1).map(layer => {
// 隐藏我们不需要的demotiles样式中的图层
if (layer.id.startsWith('geolines')) {
layer.layout = {...layer.layout || {}, visibility: 'none'};
// 过滤美国多边形
} else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {
layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];
}
return layer;
})
]
})
});