Recommended way to switch tile urls in mapbox-gl-j

2020-05-24 05:31发布

问题:

Situation

We render a raster layer to the map. The layer's source has an initial tile-url. Now we want to change the tile-url of the source and trigger a reload for the new tiles. E.g. we have tiles for different points in time and we want to step through the different time steps.

What can be done in mapbox-gl@0.21.0

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

This works fine. But, of course, using private methods is bad practice; see the reason below:

What can be done with the current version from github (Latest commit 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();

It has to be done this way, because the former TilePyramid has been refactored to a SourceCache. Here we are calling reload() on the SourceCache not the RasterTileSource. It seems that we don't have to use any private methods anymore, though this still looks like undocumented API, which may break in future versions.

Also there seems to be an issue with a memory leak when calling reload(): https://github.com/mapbox/mapbox-gl-js/issues/2266

Additionally the cache gets cleared when calling reload(). Which for now doesn't seem to be an issue.

// 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

The SourceCache has the RasterTileSource instance as a private _source field.

Question

What is the recommended way to do something like this? Is this a feature being worked on? Is there an explanation why this isn't a feature (yet) or never will be?

回答1:

It sounds like you're trying to change the URL of a raster source. The proper way to do this in GL JS is to remove the source and then add a new source with the same id and the new 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'], ...});