在 mapbox-gl-js 中切换瓦片 url 的推荐方法

问题描述 投票:0回答:3

情况

我们渲染一个raster层到地图。层的源有一个初始的 tile-url。现在我们要更改源的 tile-url 并触发新图块的重新加载。例如。我们有不同时间点的图块,我们想逐步执行不同的时间步骤。

可以做什么

[email protected]

map.addSource('tile-source', {...});
map.addLayer('tile-layer', {source: 'tile-source', ...});

// react to a button click or what ever to trigger tile url change
...
const source = map.getSource('tile-source');
source.tiles = ['new-tile-url'];
source._pyramid.reload();

这很好用。但是,当然,使用私有方法是不好的做法;原因见下:

github 的当前版本可以做什么(最新提交 b155118,2016-07-28)

// init map, add layer, add source, like above
const source = map.getSource('tile-source');
source.tiles = ['new-tile-url'];

map.styles.sources['tile-source'].reload();

不得不这样,因为之前的

TilePyramid
已经重构为一个
SourceCache
了。在这里,我们在
reload()
上调用
SourceCache
而不是
RasterTileSource
。似乎我们不必再使用任何私有方法了,尽管这看起来仍然像未记录的 API,在未来的版本中可能会中断。

调用

reload()
时似乎也存在内存泄漏问题: https://github.com/mapbox/mapbox-gl-js/issues/2266

此外,调用

reload()
时缓存会被清除。现在这似乎不是问题。

// This yields a `RasterTileSource` instance
map.getSource('tile-source'); 

// This yields a `SourceCache` instance
map.styles.sources['tile-source'];

// What's really confusing too, at least namingwise
map.getStyle(); // <-- Yields the maps (visual) style

SourceCache
具有
RasterTileSource
实例作为私有
_source
字段。

问题

做这样的事情推荐的方法是什么?这是正在开发的功能吗?是否有解释为什么这不是一个功能(还)或永远不会是?

mapbox-gl mapbox-gl-js
3个回答
8
投票

听起来您正在尝试更改

raster
源的 URL。在 GL JS 中执行此操作的正确方法是删除源,然后添加具有相同 ID 和新 URL 的新源。

map.addSource('tile-source', {...});
map.addLayer('tile-layer', {source: 'tile-source', ...});

// react to a button click or what ever to trigger tile url change
...
map.removeSource('tile-source');
map.addSource('tile-source', {tiles: ['new-tile-url'], ...});

4
投票

这是另一种更改 Mapbox GL JS 图层 URL 而不删除和添加源和图层的方法。

// Set the tile URL to a cache-busting URL (to circumvent browser caching behavior):
map.getSource('source-id').tiles = [ `http://some.url/{z}/{x}/{y}.pbf?dt=${Date.now()}` ]

// Remove the tiles for a particular source
map.style.sourceCaches['source-id'].clearTiles()

// Load the new tiles for the current viewport (map.transform -> viewport)
map.style.sourceCaches['source-id'].update(map.transform)

// Force a repaint, so that the map will be repainted without you having to touch the map
map.triggerRepaint()

我想出了解决办法。而不是 sourceCache 尝试 _sourceCache 函数并在您的 id 之前键入“其他”。

map.style._sourceCaches['other:wms-source'].clearTiles();
map.style._sourceCaches['other:wms-source'].update(map.transform)

https://github.com/mapbox/mapbox-gl-js/issues/2941#issuecomment-518631078


0
投票

Mapbox GL JS v2.13.0 于 2023 年 2 月 22 日发布

Add methods for changing a raster tile source dynamically (e.g. setTiles, setUrl).
(#12352)

所以现在您可以在不删除图层和源的情况下更新光栅源。

© www.soinside.com 2019 - 2024. All rights reserved.