Skip to content

Instantly share code, notes, and snippets.

@AbelVM
Last active March 15, 2025 12:41
Show Gist options
  • Save AbelVM/db9c22ae61ba442fa90933e6cb642315 to your computer and use it in GitHub Desktop.
Save AbelVM/db9c22ae61ba442fa90933e6cb642315 to your computer and use it in GitHub Desktop.
Refresh MapLibre layer' source when the tiles are older than a given TTL
window.__refresh__ = false; // global flag to check whether to refresh or not
const ttl = 1000 * 60 * 60; // tile time to live, ms
const map = new maplibregl.Map(
{
...,
transformRequest: (url, resourceType) => {
if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {
if(window.__refresh__){
return {'url':`${url}${(url.indexOf('?') > -1) ? '&' : '?'}tick=${Date.now()}`}
}else{
return {'url':url}
}
}
}
}
);
map.on('idle', inputlayer, e => {
const
source = e.sourceId,
sourceCache = this.style.sourceCaches[source],
sampleTileZXY = sourceCache.getRenderableIds().map((id) => sourceCache.getTileByID(id).tileID.canonical)[0],
http = new XMLHttpRequest(),
datelimit = new Date(Date.now() - ttl).toGMTString(),
sourceURL = this.getSource('source').url || this.getSource('source').tiles[0],
tileURL = sourceURL.replace('{z}', sampleTileZXY.z).replace('{x}', sampleTileZXY.x).replace('{y}', sampleTileZXY.y);
http.open('HEAD', url, false);
http.setRequestHeader('If-Modified-Since', datelimit);
http.send();
window.__refresh__ = http.status !== 304;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment