### Install Dependencies and Start Local Development Server
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/README.md
Installs project dependencies and starts a local development server for live preview. Changes are reflected without restarting.
```bash
npm install
npm start
```
--------------------------------
### Clone and Install Project Dependencies
Source: https://github.com/muimsd/map-gl-offline/blob/main/README.md
Clone the Map GL Offline repository and install its dependencies using npm. This is the initial setup step for contributing to the project.
```bash
git clone https://github.com/muimsd/map-gl-offline.git
cd map-gl-offline && npm install
```
--------------------------------
### Install Dependencies
Source: https://github.com/muimsd/map-gl-offline/blob/main/examples/maplibre/README.md
Installs the necessary project dependencies.
```bash
npm install
```
--------------------------------
### Run Development Server
Source: https://github.com/muimsd/map-gl-offline/blob/main/examples/maplibre/README.md
Starts the development server to run the demo application.
```bash
npm run dev
```
--------------------------------
### Install Dependencies and Initialize Mapbox GL Offline
Source: https://github.com/muimsd/map-gl-offline/blob/main/examples/mapbox-gl/README.md
Installs the necessary npm packages and initializes the map-gl-offline tool. This is a prerequisite for running the demo.
```bash
npm install
npx map-gl-offline init
```
--------------------------------
### Install Peer Dependencies
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Install either MapLibre GL JS or Mapbox GL JS as a peer dependency for map-gl-offline.
```bash
# For MapLibre GL JS
npm install maplibre-gl
# For Mapbox GL JS
npm install mapbox-gl
```
--------------------------------
### Install map-gl-offline via npm
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/intro.md
Install the library using npm for project integration.
```bash
npm install map-gl-offline
```
--------------------------------
### MapLibre GL JS Quick Start
Source: https://github.com/muimsd/map-gl-offline/blob/main/README.md
Integrate Map GL Offline with MapLibre GL JS. This example shows how to initialize the map and add the offline manager control.
```typescript
import maplibregl from 'maplibre-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
import 'maplibre-gl/dist/maplibre-gl.css';
import 'map-gl-offline/style.css';
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=YOUR_KEY',
center: [-74.006, 40.7128],
zoom: 12,
});
const offlineManager = new OfflineMapManager();
map.on('load', () => {
const control = new OfflineManagerControl(offlineManager, {
styleUrl: 'https://api.maptiler.com/maps/streets/style.json?key=YOUR_KEY',
mapLib: maplibregl, // enables idb:// protocol in web workers
});
map.addControl(control, 'top-right');
});
```
--------------------------------
### startEnhancedAutoCleanup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Alternative auto-cleanup setup with separate interval and options parameters. Returns a cleanup ID.
```APIDOC
## startEnhancedAutoCleanup(intervalHours?: number, options?: RegionCleanupOptions)
### Description
Alternative auto-cleanup setup with separate interval and options parameters. Returns a cleanup ID.
### Method
GET (assumed, based on typical SDK patterns for cleanup)
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **intervalHours** (number) - Optional - The interval in hours at which to run cleanup.
- **options** (object) - Optional - Configuration options for smart cleanup.
- **maxAge** (number) - Optional - Delete regions older than this many days.
- **maxStorageSize** (number) - Optional - Keep total storage under this size in bytes.
- **maxRegions** (number) - Optional - Keep at most this many regions.
- **priorityPatterns** (string[]) - Optional - Protect regions matching these patterns.
- **onProgress** (function) - Optional - Callback function to report progress.
### Request Example
```typescript
const cleanupId = await manager.startEnhancedAutoCleanup(12, {
// Every 12 hours
maxAge: 7,
maxRegions: 5,
});
```
### Response
#### Success Response (200)
- **cleanupId** (string) - An identifier for the set up auto-cleanup process.
```
--------------------------------
### CDN Setup for map-gl-offline
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Include map-gl-offline via script tags for use without a bundler. The library is exposed as the `mapgloffline` global.
```html
```
--------------------------------
### Minimal MapLibre GL JS Setup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/examples.md
Sets up a basic MapLibre GL JS map with the map-gl-offline control. Ensure maplibre-gl and map-gl-offline CSS are imported.
```typescript
import maplibregl from 'maplibre-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
import 'maplibre-gl/dist/maplibre-gl.css';
import 'map-gl-offline/style.css';
const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [0, 0],
zoom: 2,
});
const manager = new OfflineMapManager();
const control = new OfflineManagerControl(manager, {
styleUrl: 'https://demotiles.maplibre.org/style.json',
});
map.addControl(control, 'top-right');
```
--------------------------------
### Environment Setup for API Keys
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Configure your API keys for MapTiler styles and Mapbox GL JS by creating a .env file. Obtain keys from MapTiler or Mapbox.
```env
# For MapTiler styles (MapLibre)
VITE_MAPTILER_API_KEY=your_maptiler_key_here
# For Mapbox GL JS
VITE_MAPBOX_ACCESS_TOKEN=your_mapbox_token_here
```
--------------------------------
### Basic Mapbox GL JS Setup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/examples.md
Configures a Mapbox GL JS map with the map-gl-offline control. Requires a Mapbox access token and appropriate CSS imports.
```typescript
import mapboxgl from 'mapbox-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
import 'mapbox-gl/dist/mapbox-gl.css';
import 'map-gl-offline/style.css';
mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-74.006, 40.7128],
zoom: 12,
});
const manager = new OfflineMapManager();
const control = new OfflineManagerControl(manager, {
styleUrl: 'mapbox://styles/mapbox/streets-v12',
accessToken: mapboxgl.accessToken,
theme: 'dark',
});
map.addControl(control, 'top-right');
```
--------------------------------
### Mapbox GL JS Quick Start
Source: https://github.com/muimsd/map-gl-offline/blob/main/README.md
Integrate Map GL Offline with Mapbox GL JS after initializing the service worker. This example shows map initialization and adding the offline control.
```typescript
import mapboxgl from 'mapbox-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
import 'mapbox-gl/dist/mapbox-gl.css';
import 'map-gl-offline/style.css';
mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/standard',
center: [-74.006, 40.7128],
zoom: 12,
});
const offlineManager = new OfflineMapManager();
map.on('load',
() =>
map.addControl(
new OfflineManagerControl(offlineManager, {
styleUrl: 'mapbox://styles/mapbox/standard',
accessToken: mapboxgl.accessToken,
}),
'top-right',
),
);
```
--------------------------------
### Two-Tier Setup for App Shipping
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/examples.md
Download a low-zoom global overview followed by high-zoom per-city regions for efficient app shipping. Ensure the overview's `maxZoom` overlaps each city's `minZoom` to avoid seams.
```typescript
import type { BoundingBox, DownloadRegionProgress } from 'map-gl-offline';
const STYLE_URL = 'mapbox://styles/mapbox/standard';
const opts = {
accessToken: mapboxgl.accessToken, // accepts `string | null` — no cast needed
onProgress: ({ phase, percentage }: DownloadRegionProgress) =>
console.log(`[${phase}] ${percentage.toFixed(1)}%`),
};
// 1) Whole planet, low zoom only (~5,500 tiles/source) — countries, major cities
await manager.downloadRegion(
{
id: 'global-overview',
name: 'Global overview',
bounds: [[-180, -85.0511], [180, 85.0511]], // ±85.0511° = Web Mercator cutoff
minZoom: 0,
maxZoom: 6,
styleUrl: STYLE_URL,
multipleRegions: true,
},
opts,
);
// 2) High-detail per city — tight bbox per place your users actually go
const cities: Array<{ id: string; name: string; bounds: BoundingBox }> = [
{ id: 'nyc', name: 'New York', bounds: [[-74.05, 40.68], [-73.90, 40.82]] },
{ id: 'london', name: 'London', bounds: [[-0.25, 51.43], [0.02, 51.57]] },
];
for (const city of cities) {
await manager.downloadRegion(
{
...city,
minZoom: 6, // overlaps the overview's maxZoom — clean handoff, no seam
maxZoom: 14, // street-level detail
styleUrl: STYLE_URL,
multipleRegions: true,
},
opts,
);
}
```
--------------------------------
### HTML Structure for Map Container
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Basic HTML setup including a div element with the ID 'map' to serve as the container for the map. Ensure the script tag points to your main application file.
```html
Offline Map Demo
```
--------------------------------
### Setup and Stop Automatic Data Cleanup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/configuration.md
Configure automatic data cleanup based on interval and age, or stop specific or all cleanup tasks.
```typescript
const cleanupId = await manager.setupAutoCleanup({
intervalHours: 24, // Run every 24 hours
maxAge: 30, // Remove data older than 30 days
});
// Stop a specific auto cleanup
await manager.stopAutoCleanup(cleanupId);
// Stop all auto cleanups
await manager.stopAllAutoCleanup();
```
--------------------------------
### Import Modules for Mapbox GL JS Setup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Import necessary modules and styles when using map-gl-offline with Mapbox GL JS.
```typescript
import mapboxgl from 'mapbox-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
// Import styles
import 'mapbox-gl/dist/mapbox-gl.css';
import 'map-gl-offline/style.css';
```
--------------------------------
### Import Modules for MapLibre GL JS Setup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Import necessary modules and styles when using map-gl-offline with MapLibre GL JS.
```typescript
import maplibregl from 'maplibre-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
// Import styles
import 'maplibre-gl/dist/maplibre-gl.css';
import 'map-gl-offline/style.css';
```
--------------------------------
### Start Enhanced Automatic Region Cleanup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
An alternative method to set up automatic cleanup with separate parameters for interval and cleanup options. Returns a cleanup ID.
```typescript
const cleanupId = await manager.startEnhancedAutoCleanup(12, {
// Every 12 hours
maxAge: 7,
maxRegions: 5,
});
```
--------------------------------
### List All Region Options
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Use `listRegions` to get a list of available region configurations without any associated database metadata. This is useful for understanding available offline map options.
```typescript
const regions = await manager.listRegions();
regions.forEach(r => console.log(`${r.name}: ${r.id}`));
```
--------------------------------
### Language Switching and Translation
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/examples.md
Demonstrates how to get the current language, switch to a different language (e.g., Arabic), and retrieve translated strings. Requires `i18n` and `t` from 'map-gl-offline'.
```typescript
import { i18n, t } from 'map-gl-offline';
// Get current language
console.log(i18n.getLanguage()); // 'en'
// Switch to Arabic (RTL layout is applied automatically)
i18n.setLanguage('ar');
// Get a translated string
const label = t('regionForm.downloadRegion'); // Translated text for the current language
// List available languages
const languages = i18n.getAvailableLanguages();
// [{ code: 'en', name: 'English', nativeName: 'English' },
// { code: 'ar', name: 'Arabic', nativeName: 'العربية' }]
```
--------------------------------
### Get Comprehensive Storage Analytics
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Use `getComprehensiveStorageAnalytics` to obtain a detailed report on storage usage across all resource types (tiles, fonts, sprites, glyphs) and regions. This report includes aggregated statistics and actionable recommendations for storage optimization.
```typescript
const report = await manager.getComprehensiveStorageAnalytics();
// Overall storage
console.log(`Total storage: ${report.totalStorageSize} bytes`);
console.log(`Storage by type:`, report.storageByType);
// { tiles: 52428800, fonts: 1048576, sprites: 524288, glyphs: 2097152 }
// Per-resource statistics
console.log(`Tiles: ${report.tiles.count}, avg size: ${report.tiles.averageSize}`);
console.log(`Fonts: ${report.fonts.count}`);
console.log(`Sprites: ${report.sprites.count}`);
console.log(`Glyphs: ${report.glyphs.count}`);
// Region summary
console.log(`Regions: ${report.regions.totalRegions}`);
console.log(`Expired: ${report.regions.expiryDistribution.expired}`);
// Actionable recommendations
report.recommendations.forEach(rec => console.log(`- ${rec}`));
// e.g., "High tile count (65000). Consider reducing zoom levels or region sizes."
// e.g., "3 expired regions found. Run cleanup to free storage."
```
--------------------------------
### Build Static Content for Deployment
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/README.md
Generates static website content into the 'build' directory, ready for deployment.
```bash
npm run build
```
--------------------------------
### Get Tile Statistics
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Retrieve statistics for tiles. Pass a `styleId` to filter statistics for a specific style, or omit it to get an aggregate across all styles.
```typescript
const tileStats = await manager.getTileStats('my-style-id'); // Or omit styleId for aggregate
```
--------------------------------
### Accessing Constants
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Illustrates how to import and use predefined constants for database names, download defaults, tile configurations, and error messages.
```typescript
import { DB_NAME, DOWNLOAD_DEFAULTS, TILE_CONFIG, ERROR_MESSAGES } from 'map-gl-offline';
const batchSize = DOWNLOAD_DEFAULTS.BATCH_SIZE; // 10
const maxZoom = TILE_CONFIG.MAX_ZOOM; // 24
```
--------------------------------
### Get Region Analytics and Size
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/configuration.md
Retrieve storage analytics for all regions or the specific size of a single region.
```typescript
// Get storage analytics per region
const analytics = await manager.getRegionAnalytics();
// Get size of a specific region
const size = await manager.getRegionSize(regionId);
```
--------------------------------
### TileService Get Tile Stats
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Retrieves statistics for tiles associated with a specific style ID using the TileService.
```typescript
// Or using the service instance directly
const stats = await tileService.getTileStats('style_123');
```
--------------------------------
### Get Current Style URL
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Retrieves the currently configured style URL that is used for new region downloads.
```typescript
const url = control.getCurrentStyleUrl();
```
--------------------------------
### Run Development and Test Commands
Source: https://github.com/muimsd/map-gl-offline/blob/main/README.md
Commands to run the development server, execute unit tests, or build the library for the Map GL Offline project.
```bash
npm run dev # dev harness
npm test # unit tests
npm run build # library
```
--------------------------------
### Get Glyph Statistics
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Retrieve aggregated statistics for all glyphs stored offline. This method provides an overview of glyph resource usage.
```typescript
const glyphStats = await manager.getGlyphStats();
```
--------------------------------
### Tile Key Generation and Format
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/architecture.md
Illustrates how to use the `createTileKey()` utility to generate composite keys for efficient tile lookup. The key format is `{styleId}:{sourceId}:{z}:{x}:{y}.{extension}`.
```typescript
// Key format: {styleId}:{sourceId}:{z}:{x}:{y}.{extension}
import { createTileKey, parseTileKey } from 'map-gl-offline';
const key = createTileKey(x, y, z, styleId, sourceId, extension);
// Examples
const key = 'mapbox-streets-v12:mapbox.mapbox-streets-v8:14:4824:6159.pbf';
const rasterKey = 'satellite:mapbox.satellite:12:1204:1540.jpg';
```
--------------------------------
### Get Sprite Statistics
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Retrieve aggregated statistics for all sprites stored offline. This method provides an overview of sprite resource usage.
```typescript
const spriteStats = await manager.getSpriteStats();
```
--------------------------------
### Get Font Statistics
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Retrieve aggregated statistics for all fonts stored offline. This method provides an overview of font resource usage.
```typescript
const fontStats = await manager.getFontStats();
```
--------------------------------
### Initialize Service Worker for Mapbox GL JS (Vite Plugin)
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/intro.md
Configure Vite to automatically copy the Service Worker files during the build process.
```javascript
// vite.config.js
import { offlineSwPlugin } from 'map-gl-offline/vite-plugin';
export default defineConfig({
plugins: [offlineSwPlugin()],
});
```
--------------------------------
### Initialize Map with Mapbox GL JS
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Configure and initialize a new map instance using Mapbox GL JS, including setting the access token.
```typescript
mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/standard',
center: [-74.006, 40.7128],
zoom: 12,
});
```
--------------------------------
### setupAutoCleanup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Set up automatic periodic cleanup. Returns a cleanup ID that can be used to stop this specific auto-cleanup.
```APIDOC
## setupAutoCleanup(options?: RegionCleanupOptions & { intervalHours?: number })
### Description
Set up automatic periodic cleanup. Returns a cleanup ID that can be used to stop this specific auto-cleanup. The cleanup runs using the smart cleanup algorithm with the provided options.
### Method
GET (assumed, based on typical SDK patterns for cleanup)
### Endpoint
N/A (SDK method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (object) - Optional - Configuration options for automatic cleanup.
- **intervalHours** (number) - Optional - The interval in hours at which to run cleanup (default 24).
- **maxAge** (number) - Optional - Delete regions older than this many days.
- **maxStorageSize** (number) - Optional - Keep total storage under this size in bytes.
- **maxRegions** (number) - Optional - Keep at most this many regions.
- **priorityPatterns** (string[]) - Optional - Protect regions matching these patterns.
- **onProgress** (function) - Optional - Callback function to report progress.
### Request Example
```typescript
const cleanupId = await manager.setupAutoCleanup({
intervalHours: 24, // Run every 24 hours (default)
maxAge: 30, // Delete regions older than 30 days
maxStorageSize: 1024 * 1024 * 1024, // 1GB limit
priorityPatterns: ['important'],
});
// Later, stop this specific auto-cleanup
await manager.stopAutoCleanup(cleanupId);
```
### Response
#### Success Response (200)
- **cleanupId** (string) - An identifier for the set up auto-cleanup process.
```
--------------------------------
### Mapbox GL JS Integration
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/intro.md
Integrate map-gl-offline with Mapbox GL JS. This example shows how to add the OfflineManagerControl to a Mapbox map.
```typescript
import mapboxgl from 'mapbox-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
import 'mapbox-gl/dist/mapbox-gl.css';
import 'map-gl-offline/style.css';
mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/standard',
center: [-74.006, 40.7128],
zoom: 12,
});
const offlineManager = new OfflineMapManager();
map.on('load', () => {
const control = new OfflineManagerControl(offlineManager, {
styleUrl: 'mapbox://styles/mapbox/standard',
accessToken: mapboxgl.accessToken,
});
map.addControl(control, 'top-right');
});
```
--------------------------------
### MapLibre GL JS Integration
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/intro.md
Integrate map-gl-offline with MapLibre GL JS. This example shows how to add the OfflineManagerControl to a MapLibre map.
```typescript
import maplibregl from 'maplibre-gl';
import { OfflineMapManager, OfflineManagerControl } from 'map-gl-offline';
import 'maplibre-gl/dist/maplibre-gl.css';
import 'map-gl-offline/style.css';
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=YOUR_KEY',
center: [-74.006, 40.7128],
zoom: 12,
});
const offlineManager = new OfflineMapManager();
map.on('load', () => {
const control = new OfflineManagerControl(offlineManager, {
styleUrl: 'https://api.mwtiler.com/maps/streets/style.json?key=YOUR_KEY',
mapLib: maplibregl, // enables idb:// protocol in web workers
});
map.addControl(control, 'top-right');
});
```
--------------------------------
### Initialize Map with MapLibre GL JS
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Configure and initialize a new map instance using MapLibre GL JS.
```typescript
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=YOUR_API_KEY',
center: [-74.006, 40.7128],
zoom: 12,
});
```
--------------------------------
### Utilities - Constants
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Provides access to predefined constants for database names, download defaults, tile configurations, and error messages.
```APIDOC
## Utilities - Constants
### Description
Provides access to predefined constants for database names, download defaults, tile configurations, and error messages.
### Constants
- `DB_NAME`: The name of the database.
- `DOWNLOAD_DEFAULTS`: Default settings for downloads (e.g., `BATCH_SIZE`).
- `TILE_CONFIG`: Configuration related to tiles (e.g., `MAX_ZOOM`).
- `ERROR_MESSAGES`: Standard error messages.
### Usage
```typescript
import { DOWNLOAD_DEFAULTS, TILE_CONFIG } from 'map-gl-offline';
const batchSize = DOWNLOAD_DEFAULTS.BATCH_SIZE; // 10
const maxZoom = TILE_CONFIG.MAX_ZOOM; // 24
```
```
--------------------------------
### IndexedDB Initialization and Upgrade
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/architecture.md
Initializes the IndexedDB database and handles schema migrations during the upgrade process. Creates object stores for regions, tiles, styles, sprites, glyphs, fonts, and models.
```typescript
// Database structure (version 4)
const db = await openDB('offline-map-db', DB_VERSION, {
upgrade(db, oldVersion, _newVersion, transaction) {
// Create stores for fresh installs (`regions` is deprecated but still created)
const stores = ['regions', 'tiles', 'styles', 'sprites', 'glyphs', 'fonts', 'models'];
for (const store of stores) {
if (!db.objectStoreNames.contains(store)) {
db.createObjectStore(store, { keyPath: 'key' });
}
}
// Migration: v2 -> v3: move regions into styles.regions[]
if (oldVersion > 0 && oldVersion < 3) {
migrateRegionsToStyles(transaction);
}
// v3 -> v4 adds the `models` store; no data movement needed.
},
});
```
--------------------------------
### Perform Smart Cleanup with Options
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Runs an intelligent cleanup process based on configurable criteria like age, storage size, region count, and priority patterns. Includes progress callbacks and returns detailed results.
```typescript
const result = await manager.performSmartCleanup({
maxAge: 14, // Delete regions older than 14 days
maxStorageSize: 500 * 1024 * 1024, // Keep total storage under 500MB
maxRegions: 10, // Keep at most 10 regions
priorityPatterns: ['downtown', 'home'], // Protect regions matching these patterns
onProgress: progress => {
console.log(
`[${progress.phase}] ${progress.completed}/${progress.total} - ${progress.message}`
);
// [scanning] 0/100 - Scanning offline regions...
// [analyzing] 30/100 - Analyzing region data...
// [cleaning] 75/100 - Deleted region: Old Region
},
});
console.log(`Scanned: ${result.scannedRegions}`);
console.log(`Expired: ${result.expiredRegions}`);
console.log(`Deleted: ${result.deletedRegions}`);
console.log(`Preserved: ${result.preservedRegions}`);
console.log(`Freed: ${(result.freedSpace / 1024 / 1024).toFixed(1)} MB`);
result.recommendations.forEach(rec => console.log(`Tip: ${rec}`));
```
--------------------------------
### Initialize Service Worker for Mapbox GL JS (CLI)
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/intro.md
Initialize the Service Worker for Mapbox GL JS offline support using the CLI. This is the recommended method.
```bash
npx map-gl-offline init
```
--------------------------------
### Tile Download Options
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Options that can be passed to `downloadRegion`, `downloadTiles`, or `ResourceService.downloadTilesWithOptions` to control the tile downloading process.
```APIDOC
## Tile Download Options
### Description
These options configure the behavior of the tile downloader, affecting which tiles are downloaded, how network requests are handled, and performance tuning.
### Parameters
#### Query Parameters
- **skipKnownSparseSources** (boolean) - Optional - Default: `true` - Hard-skip Mapbox Standard sub-tilesets that are sparse-by-design across the whole planet — `mapbox.indoor-v3`, `mapbox.landmark-pois-v1`, `mapbox.procedural-buildings-v1` — *before* any network request is issued. Eliminates the 404s these would otherwise log in devtools. Set `false` to fall through to the probe-only path.
- **probeSourcesBeforeDownload** (boolean) - Optional - Default: `true` - Fetch 3 representative tiles (start, middle, end) per source before committing its full plan. Majority-404 sources are dropped entirely. Keeps the console clean for composite styles that reference sparse tilesets which only have data at specific locations.
- **skipExisting** (boolean) - Optional - Default: `true` - Skip tiles already present in IndexedDB.
- **batchSize** (number) - Optional - Default: `10` - Concurrent tiles per batch.
- **maxRetries** (number) - Optional - Default: `3` - Per-tile retry count before giving up.
- **timeout** (number) - Optional - Default: `10000` - Per-tile fetch timeout in ms.
- **retryDelay** (number) - Optional - Default: `1000` - Base delay between retries.
- **bandwidthLimit** (number) - Optional - No default - KB/s ceiling to throttle downloads.
- **validateTiles** (boolean) - Optional - Default: `false` - Validate tile payloads after download.
- **compressTiles** (boolean) - Optional - Default: `false` - Compress tiles before storage.
```
--------------------------------
### Get Specific Region Size
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Use `getRegionSize` to determine the storage size in bytes for a specific region's tiles. An optional `styleId` can be provided to filter by a particular style.
```typescript
const sizeInBytes = await manager.getRegionSize('my-region');
console.log(`Region uses ${(sizeInBytes / 1024 / 1024).toFixed(1)} MB`);
```
--------------------------------
### Import MBTiles from File
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/examples.md
Import map data from an MBTiles file selected by the user. Displays progress and success/failure messages.
```typescript
// HTML:
document.getElementById('import-file').addEventListener('change', async e => {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
const result = await manager.importRegion({
file,
format: 'mbtiles',
overwrite: false,
onProgress: p => console.log(p.message),
});
if (result.success) {
alert(`Imported "${result.regionId}" with ${result.statistics.tilesImported} tiles`);
} else {
alert(`Import failed: ${result.message}`);
}
});
```
--------------------------------
### Utilities - Tile Key Utilities
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Functions for creating, parsing, and deriving tile keys and extensions.
```APIDOC
## Utilities - Tile Key Utilities
### Description
Functions for creating, parsing, and deriving tile keys and extensions.
### Functions
- `createTileKey(x, y, z, styleId, sourceId, ext): string`: Creates a canonical tile-store key.
- `parseTileKey(key: string): { styleId, sourceId, z, x, y, ext } | null`: Parses a tile key into its components.
- `deriveTileExtension(tiles: unknown): string`: Derives the tile extension from a source's `tiles` array.
- `extractTileExtensionFromUrl(url: string): string`: Extracts the tile extension from a URL.
### `createTileKey(x, y, z, styleId, sourceId, ext): string`
Returns `{styleId}:{sourceId}:{z}:{x}:{y}.{ext}` — the canonical tile-store key.
### `parseTileKey(key: string): { styleId, sourceId, z, x, y, ext } | null`
Inverse of `createTileKey`. Returns null for malformed keys.
### `deriveTileExtension(tiles: unknown): string`
Takes a source's `tiles` array, returns the extension of the first URL (or `"pbf"`). Used when generating per-source tile URL templates.
### `extractTileExtensionFromUrl(url: string): string`
Returns the last dotted segment of the URL path before `?` / `#` / end. For Mapbox v4 `.vector.pbf` URLs this gives `"pbf"` — which matches what `tileService.extractExtension` stores the tile key under. Added in 0.8.1 to dedupe an extract-regex that used to live (incompatibly) in two places; `deriveTileExtension` now delegates to it.
### Usage
```typescript
import {
createTileKey,
parseTileKey,
deriveTileExtension,
extractTileExtensionFromUrl,
} from 'map-gl-offline';
```
```
--------------------------------
### Mapbox GL JS Service Worker Initialization
Source: https://github.com/muimsd/map-gl-offline/blob/main/README.md
Initialize the Mapbox GL JS Service Worker for offline support. Choose one of the provided methods: CLI, Vite plugin, or manual copy.
```bash
npx map-gl-offline init # CLI (recommended)
# or add to vite.config.js:
# import { offlineSwPlugin } from 'map-gl-offline/vite-plugin';
# plugins: [offlineSwPlugin()]
# or manually: cp node_modules/map-gl-offline/dist/idb-offline-sw.js public/
```
--------------------------------
### Setup Automatic Region Cleanup
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Configures periodic automatic cleanup of regions using the smart cleanup algorithm. Returns a cleanup ID to stop this specific auto-cleanup. The interval defaults to 24 hours.
```typescript
const cleanupId = await manager.setupAutoCleanup({
intervalHours: 24, // Run every 24 hours (default)
maxAge: 30, // Delete regions older than 30 days
maxStorageSize: 1024 * 1024 * 1024, // 1GB limit
priorityPatterns: ['important'],
});
// Later, stop this specific auto-cleanup
await manager.stopAutoCleanup(cleanupId);
```
--------------------------------
### Default Download Settings
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/configuration.md
Defines the default configuration for tile downloads, including batch size, concurrency, retries, and timeouts.
```typescript
const DOWNLOAD_DEFAULTS = {
BATCH_SIZE: 10, // Tiles per batch
MAX_CONCURRENCY: 5, // Concurrent downloads
MAX_RETRIES: 3, // Retry attempts per item
TIMEOUT: 10000, // Request timeout (ms)
RETRY_DELAY: 1000, // Delay between retries (ms)
};
```
--------------------------------
### Programmatic Language Control in Map GL Offline
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/configuration.md
Use these functions to get the current language, change it, check for RTL support, translate strings, and subscribe to language change events. Ensure the 'map-gl-offline' package is imported.
```typescript
import { i18n, t } from 'map-gl-offline';
// Get current language
const lang = i18n.getLanguage(); // 'en' | 'ar'
// Change language
i18n.setLanguage('ar');
// Check if current language is RTL
const isRTL = i18n.isRTL(); // true for Arabic
// Translate a key
const title = t('app.title'); // 'Offline Manager' or 'مدير الخرائط غير المتصلة'
// Translate with interpolation
const subtitle = t('header.subtitle', { count: 3, size: '12 MB' });
// '3 regions • 12 MB total'
// Get all available languages
const languages = i18n.getAvailableLanguages();
// [{ code: 'en', name: 'English', nativeName: 'English' },
// { code: 'ar', name: 'Arabic', nativeName: 'العربية' }]
// Subscribe to language changes
const unsubscribe = i18n.subscribe(() => {
console.log('Language changed to:', i18n.getLanguage());
// Re-render your UI here
});
// Later, unsubscribe
unsubscribe();
```
--------------------------------
### Mapbox Standard Style with 3D Buildings
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/examples.md
Demonstrates using the Mapbox Standard style with 3D buildings, which involves resolving imported styles and handling sparse tilesets. The downloader automatically drops unsupported sources.
```typescript
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/standard',
center: [-73.985, 40.748],
zoom: 15,
pitch: 60,
bearing: -17,
});
const manager = new OfflineMapManager();
const control = new OfflineManagerControl(manager, {
styleUrl: 'mapbox://styles/mapbox/standard',
accessToken: mapboxgl.accessToken,
});
map.addControl(control, 'top-right');
// Download a region with 3D buildings. The tile downloader probes each
// source before committing — sparse Mapbox tilesets (indoor, landmark-POIs,
// procedural-buildings) that return 404 for most coordinates are
// automatically dropped, keeping the console clean.
await manager.downloadRegion(
{
id: 'manhattan-3d',
name: 'Manhattan 3D',
bounds:
[
[-74.02, 40.7],
[-73.95, 40.78],
],
minZoom: 12,
maxZoom: 16,
styleUrl: 'mapbox://styles/mapbox/standard',
},
{
accessToken: mapboxgl.accessToken,
provider: 'mapbox',
onProgress: ({ phase, percentage }) => console.log(`[${phase}] ${percentage.toFixed(0)}%`),
}
);
```
--------------------------------
### Download, List, Get, and Delete Offline Map Regions
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Use OfflineMapManager to download a region end-to-end, list all stored regions, retrieve a specific region by ID, and delete a region. The download process includes progress updates.
```typescript
const offlineManager = new OfflineMapManager();
// Download a region end-to-end
await offlineManager.downloadRegion(
{
id: 'downtown',
name: 'Downtown Area',
bounds: [
[-74.0559, 40.7128], // Southwest [lng, lat]
[-74.0059, 40.7628], // Northeast [lng, lat]
],
minZoom: 10,
maxZoom: 16,
styleUrl: 'https://api.maptiler.com/maps/streets/style.json?key=YOUR_KEY',
},
{
onProgress: ({ phase, percentage }) => {
console.log(`[${phase}] ${percentage.toFixed(1)}%`);
},
}
);
// List stored regions
const regions = await offlineManager.listStoredRegions();
console.log('Stored regions:', regions);
// Retrieve a stored region
const region = await offlineManager.getStoredRegion('downtown');
if (region) {
console.log(`Region: ${region.name}, created: ${new Date(region.created).toLocaleDateString()}`);
}
// Delete a region
await offlineManager.deleteRegion('downtown');
```
--------------------------------
### Prepare Service Worker for Mapbox GL JS
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/getting-started.md
Copy the Service Worker file to your public directory for Mapbox GL JS v3 compatibility.
```bash
npx map-gl-offline init
```
```js
// vite.config.js
import { offlineSwPlugin } from 'map-gl-offline/vite-plugin';
export default defineConfig({
plugins: [offlineSwPlugin()],
});
```
```bash
cp node_modules/map-gl-offline/dist/idb-offline-sw.js public/idb-offline-sw.js
```
--------------------------------
### Get Aggregate Region Analytics
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Use `getRegionAnalytics` to retrieve aggregated statistics for all stored regions, including total size, age distribution, and expiry status. This method helps in understanding the overall health and usage patterns of your offline regions.
```typescript
const analytics = await manager.getRegionAnalytics();
console.log(`Total regions: ${analytics.totalRegions}`);
console.log(`Total size: ${analytics.totalSize} bytes`);
console.log(`Average size: ${analytics.averageSize} bytes`);
// Age tracking
if (analytics.oldestRegion) {
console.log(
`Oldest: ${analytics.oldestRegion.id}, created ${new Date(analytics.oldestRegion.created)}`
);
}
if (analytics.largestRegion) {
console.log(`Largest: ${analytics.largestRegion.id}, ${analytics.largestRegion.size} bytes`);
}
// Expiry distribution
const { expired, expiringWithin24h, expiringWithin7d, neverExpiring } =
analytics.expiryDistribution;
console.log(`Expired: ${expired}, expiring soon: ${expiringWithin24h + expiringWithin7d}`);
// Breakdown by style
console.log(`Regions by style:`, analytics.regionsByStyle);
// { "style_abc123": 3, "style_def456": 1 }
```
--------------------------------
### Download Global Overview and City Details
Source: https://github.com/muimsd/map-gl-offline/blob/main/README.md
Downloads a low-zoom global basemap and high-zoom city details by setting `multipleRegions: true` for efficient app shipping. The `BoundingBox` type prevents city lists from being widened, allowing inline bounds definition.
```typescript
import mapboxgl from 'mapbox-gl';
import {
OfflineMapManager,
type BoundingBox,
type DownloadRegionProgress,
} from 'map-gl-offline';
const offlineManager = new OfflineMapManager();
const STYLE_URL = 'mapbox://styles/mapbox/standard';
const opts = {
accessToken: mapboxgl.accessToken, // `string | null` is accepted — no cast needed
onProgress: ({ phase, percentage, message }: DownloadRegionProgress) =>
console.log(`[${phase}] ${percentage.toFixed(1)}% ${message ?? ''}`),
};
// 1) Whole planet, low zoom only (~5,500 tiles/source) — countries, major cities
await offlineManager.downloadRegion(
{
id: 'global-overview',
name: 'Global overview',
bounds: [[-180, -85.0511], [180, 85.0511]], // ±85.0511° = Web Mercator cutoff
minZoom: 0,
maxZoom: 6,
styleUrl: STYLE_URL,
multipleRegions: true,
},
opts,
);
// 2) High-detail per city — tight bbox per place your users actually go
const cities: Array<{ id: string; name: string; bounds: BoundingBox }> = [
{ id: 'nyc', name: 'New York', bounds: [[-74.05, 40.68], [-73.90, 40.82]] },
{ id: 'london', name: 'London', bounds: [[-0.25, 51.43], [0.02, 51.57]] },
];
for (const city of cities) {
await offlineManager.downloadRegion(
{
id: city.id,
name: city.name,
bounds: city.bounds,
minZoom: 6, // overlaps the overview's maxZoom — clean handoff, no seam
maxZoom: 14, // street-level detail
styleUrl: STYLE_URL,
multipleRegions: true,
},
opts,
);
}
```
--------------------------------
### Configure SQL.js WASM Loader
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/configuration.md
Configure the SQL.js WASM loader by providing the URL to the WASM file or a pre-fetched binary buffer.
```typescript
import { configureSqlJs } from 'map-gl-offline';
configureSqlJs({ wasmUrl: '/static/sql-wasm/' });
// or pre-fetched binary:
configureSqlJs({ wasmBinary: myArrayBuffer });
```
--------------------------------
### loadOfflineStyles(): Promise
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/api-reference.md
Loads all available offline styles from IndexedDB. If multiple styles are found, a modal is presented for user selection. If only one style exists, it's loaded automatically.
```APIDOC
## loadOfflineStyles(): Promise
### Description
Load offline styles from IndexedDB. If only one style is stored, it is loaded automatically. If multiple styles exist, a selection modal is displayed for the user to choose.
### Parameters
None
### Request Example
```typescript
await control.loadOfflineStyles();
```
```
--------------------------------
### Tile Download Configuration
Source: https://github.com/muimsd/map-gl-offline/blob/main/docs/docs/configuration.md
Specifies the zoom levels, default tile extension, and supported extensions for tile downloads.
```typescript
const TILE_CONFIG = {
MIN_ZOOM: 0,
MAX_ZOOM: 24,
DEFAULT_EXTENSION: 'pbf',
SUPPORTED_EXTENSIONS: ['pbf', 'mvt', 'png', 'jpg', 'jpeg', 'webp', 'glb'],
};
```