Skip to content

Commit

Permalink
Use the pmtiles-protocol package for the pmtiles example
Browse files Browse the repository at this point in the history
  • Loading branch information
ahocevar committed Oct 21, 2024
1 parent a4ff0cb commit af2eef3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 59 deletions.
54 changes: 3 additions & 51 deletions examples/pmtiles.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,7 @@
import 'ol/ol.css';
import {PMTiles} from 'pmtiles';
import {apply} from 'ol-mapbox-style';
import {register as registerPMTiles} from 'pmtiles-protocol';

// Generic transformRequest function that can be used with any style
// that uses pmtiles:// URLs for sources and tiles
let styleUrl;
const pmtilesByUrl = {};
const tileUrlRegex = /^pmtiles:\/\/(.+)\/([0-9]+)\/([0-9]+)\/([0-9]+).mvt$/;
const tileCoordRegex = /\/([0-9]+)\/([0-9]+)\/([0-9]+).mvt$/;
const transformRequest = async (url, type) => {
// Workaround for broken URL handling in Safari
url = url.replace(/^pmtiles:\/\/http(s?)\/\//, 'pmtiles://http$1://');
registerPMTiles();

if (type === 'Style') {
styleUrl = url;
}
/** @type {PMTiles} */
let pmtiles;
if (url.startsWith('pmtiles://')) {
const baseUrl = url.slice(10).replace(tileCoordRegex, '');
if (!pmtilesByUrl[baseUrl]) {
pmtilesByUrl[baseUrl] = new PMTiles(
new URL(url.slice(10), styleUrl).href,
);
}
pmtiles = pmtilesByUrl[baseUrl];
}
if (!pmtiles) {
return url;
}
if (type === 'Source') {
const tileJson = await pmtiles.getTileJson(url);
return `data:application/json,${encodeURIComponent(
JSON.stringify(tileJson),
)}`;
}
if (type === 'Tiles') {
const [, baseUrl, z, x, y] = url.match(tileUrlRegex);
const tileResult = await pmtilesByUrl[baseUrl].getZxy(
Number(z),
Number(x),
Number(y),
);
const data = tileResult?.data ?? new ArrayBuffer(0);
const objectUrl = URL.createObjectURL(new Blob([data]));
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 10000);
return objectUrl;
}
return url;
};

apply('map', 'data/protomaps-dark-style.json', {
transformRequest,
});
apply('map', 'data/protomaps-dark-style.json');
33 changes: 26 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
"mini-css-extract-plugin": "^2.4.4",
"mocha": "^10.0.0",
"nanoassert": "^2.0.0",
"pmtiles": "^3.2.0",
"pmtiles-protocol": "^1.0.1",
"puppeteer": "^23.0.2",
"remove-flow-types-loader": "^1.1.0",
"rollup": "^2.70.2",
Expand Down

0 comments on commit af2eef3

Please sign in to comment.