new maplibre protocol API to avoid duplicate requests [#28]

This commit is contained in:
Brandon Liu
2022-02-18 10:44:48 +08:00
parent 47f03b768e
commit 7517b26c66

View File

@@ -436,26 +436,39 @@ export const leafletLayer = (source: PMTiles, options: any) => {
return new cls(options); return new cls(options);
}; };
export const addProtocol = (maplibregl: any) => { export class ProtocolCache {
let re = new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/); tiles: Map<string, PMTiles>;
let pmtiles_instances = new Map<string, PMTiles>();
maplibregl.addProtocol("pmtiles", (params: any, callback: any) => {
let result = params.url.match(re);
let pmtiles_url = result[1];
var instance = pmtiles_instances.get(pmtiles_url); constructor() {
this.tiles = new Map<string, PMTiles>();
}
add(p: PMTiles) {
this.tiles.set(p.url, p);
}
get(url: string) {
return this.tiles.get(url);
}
protocol(params: any, callback: any) {
const re = new RegExp(/pmtiles:\/\/(.+)\/(\d+)\/(\d+)\/(\d+)/);
const result = params.url.match(re);
const pmtiles_url = result[1];
let instance = this.tiles.get(pmtiles_url);
if (!instance) { if (!instance) {
instance = new PMTiles(pmtiles_url); instance = new PMTiles(pmtiles_url);
pmtiles_instances.set(pmtiles_url, instance); this.tiles.set(pmtiles_url, instance);
} }
let z = result[2]; const z = result[2];
let x = result[3]; const x = result[3];
let y = result[4]; const y = result[4];
var cancel = () => {}; let cancel = () => {};
instance.getZxy(+z, +x, +y).then((val) => { instance.getZxy(+z, +x, +y).then((val) => {
if (val) { if (val) {
let headers = { const headers = {
Range: "bytes=" + val.offset + "-" + (val.offset + val.length - 1), Range: "bytes=" + val.offset + "-" + (val.offset + val.length - 1),
}; };
const controller = new AbortController(); const controller = new AbortController();
@@ -482,6 +495,5 @@ export const addProtocol = (maplibregl: any) => {
cancel(); cancel();
}, },
}; };
}); }
return pmtiles_instances; }
};