UNPKG

@loaders.gl/pmtiles

Version:

Framework-independent loader for the pmtiles format

81 lines (80 loc) 2.73 kB
// loaders.gl // SPDX-License-Identifier: MIT // Copyright (c) vis.gl contributors import { TileJSONLoader } from '@loaders.gl/mvt'; // import {Source, PMTiles, Header, TileType} from 'pmtiles'; import * as pmtiles from 'pmtiles'; const { TileType } = pmtiles; /** * Parse PMTiles metdata from a PMTiles file * @param header * @param tilejsonMetadata * @param options * @param loadOptions * @returns */ export function parsePMTilesHeader(header, pmtilesMetadata, options, loadOptions) { // Ironically, to use the TileJSON loader we need to stringify the metadata again. // This is the price of integrating with the existing pmtiles library. // TODO - provide a non-standard TileJSONLoader parsers that accepts a JSON object? let tilejson = null; if (pmtilesMetadata) { try { const string = JSON.stringify(pmtilesMetadata); tilejson = TileJSONLoader.parseTextSync?.(string, loadOptions) || null; } catch (error) { // eslint-disable-next-line no-console console.warn('PMTiles metadata could not be interpreted as TileJSON', error); } } const partialMetadata = {}; if (typeof tilejson?.name === 'string') { partialMetadata.name = tilejson.name; } if (typeof tilejson?.htmlAttribution === 'string') { partialMetadata.attributions = [tilejson.htmlAttribution]; } const metadata = { ...partialMetadata, format: 'pmtiles', formatVersion: header.specVersion, attributions: [], tileMIMEType: decodeTileType(header.tileType), minZoom: header.minZoom, maxZoom: header.maxZoom, boundingBox: [ [header.minLon, header.minLat], [header.maxLon, header.maxLat] ], center: [header.centerLon, header.centerLat], centerZoom: header.centerZoom, etag: header.etag }; if (tilejson) { metadata.tilejson = tilejson; } // Application can optionally include the raw header and metadata. if (options?.includeFormatHeader) { metadata.formatHeader = header; metadata.formatMetadata = metadata; } return metadata; } /** Extract a MIME type for tiles from vector tile header */ function decodeTileType(tileType) { switch (tileType) { case TileType.Mvt: return 'application/vnd.mapbox-vector-tile'; case TileType.Png: return 'image/png'; case TileType.Jpeg: return 'image/jpeg'; case TileType.Webp: return 'image/webp'; case TileType.Avif: return 'image/avif'; default: return 'application/octet-stream'; } }