### Local Development Setup
Source: https://github.com/allartk/leaflet.offline/blob/main/README.md
Steps to set up the project for local development, including installing dependencies, building the project, and starting the documentation server.
```bash
npm i && npm run build
cd docs
npm install && npm run start
```
--------------------------------
### Project Setup and Development
Source: https://github.com/allartk/leaflet.offline/blob/main/examples/README.md
Follow these commands to set up a new project using Vite's vanilla-ts template and start the development server.
```bash
cd dir/
npm i
npm run dev
```
--------------------------------
### Install and Build Leaflet.Offline
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Installs project dependencies and builds the library. Run this to set up the project for development or to create a production build.
```bash
npm install
npm run build
```
--------------------------------
### Listen to Save Start Event
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileLayerOffline.md
Example of listening to the 'savestart' event to log the number of tiles being saved. This event is fired when a download or save operation begins.
```typescript
baseLayer.on('savestart', (status: SaveStatus) => {
console.log(`Saving ${status._tilesforSave.length} tiles`);
});
```
--------------------------------
### Example TileInfo Object
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Illustrates how to create a TileInfo object with sample data for a specific tile.
```typescript
const tileInfo: TileInfo = {
key: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png/15/16384/10924',
url: 'https://a.tile.openstreetmap.org/15/16384/10924.png',
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
x: 16384,
y: 10924,
z: 15,
createdAt: 1698765432123,
};
```
--------------------------------
### One-Minute Setup for Leaflet.offline
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/START_HERE.md
This snippet demonstrates the basic setup for integrating leaflet.offline into a Leaflet map. It includes importing necessary functions, creating a map instance, adding an offline tile layer, and initializing the save tiles control.
```typescript
import { tileLayerOffline, savetiles } from 'leaflet.offline';
import L from 'leaflet';
// Create map
const map = L.map('map').setView([51.5, -0.1], 13);
// Add offline tile layer
const layer = tileLayerOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap',
}).addTo(map);
// Add save/clear buttons
savetiles(layer, {
zoomlevels: [13, 14, 15],
}).addTo(map);
// Done! Users can now download tiles for offline use.
```
--------------------------------
### Example Usage of StoredTile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Demonstrates how to create and use a StoredTile object, including accessing its blob size.
```typescript
const storedTile: StoredTile = {
key: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png/15/8192/5462',
url: 'https://a.tile.openstreetmap.org/15/8192/5462.png',
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
x: 8192,
y: 5462,
z: 15,
createdAt: 1698765432123,
blob: new Blob([/* PNG/JPEG data */], { type: 'image/png' }),
};
// Calculate total storage size
const totalBytes = storedTile.blob.size;
```
--------------------------------
### ControlSaveTiles setStorageSize Example
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Example demonstrating how to use the setStorageSize method to get the number of cached tiles and log it to the console.
```typescript
const saveControl = savetiles(baseLayer, {});
saveControl.setStorageSize().then((count) => {
console.log(`${count} tiles cached`);
});
```
--------------------------------
### Example StoredTile Object
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Demonstrates the structure of a StoredTile object, including TileInfo properties and the image Blob.
```typescript
const storedTile: StoredTile = {
key: '...',
url: '...',
urlTemplate: '...',
x: 16384,
y: 10924,
z: 15,
createdAt: 1698765432123,
blob: new Blob([/* image data */], { type: 'image/png' }),
};
```
--------------------------------
### Example SaveTileOptions Configuration
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Illustrates setting custom options for the savetiles factory function, including zoom levels, parallel downloads, and custom confirmation dialogs.
```typescript
const options: SaveTileOptions = {
zoomlevels: [13, 14, 15],
maxZoom: 19,
parallel: 20,
alwaysDownload: false,
saveText: 'Download',
rmText: 'Clear',
confirm: (status, success) => {
if (confirm(`Cache ${status._tilesforSave.length} tiles?`)) {
success();
}
},
position: 'topright',
};
const control = savetiles(baseLayer, options);
```
--------------------------------
### Install Leaflet.offline with npm
Source: https://github.com/allartk/leaflet.offline/blob/main/README.md
Install the package and its dependencies using npm. This command downloads the library into your existing project.
```bash
npm install leaflet.offline
```
--------------------------------
### Save Tiles Control Initialization with Options
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Example demonstrating how to initialize the save tiles control with a comprehensive set of configuration options. Includes custom button text, zoom level restrictions, bounds, parallel download settings, and custom confirmation dialogs.
```typescript
const saveControl = savetiles(baseLayer, {
saveText: '',
rmText: '',
maxZoom: 17,
saveWhatYouSee: false,
zoomlevels: [13, 14, 15],
bounds: L.latLngBounds([[52.0, 5.0], [52.1, 5.1]]),
parallel: 20,
alwaysDownload: false,
confirm: (status, success) => {
if (confirm(`Save ${status._tilesforSave.length} tiles?`)) {
success();
}
},
confirmRemoval: (status, success) => {
if (confirm('Clear all offline tiles?')) {
success();
}
},
position: 'topright',
});
```
--------------------------------
### Example Usage of TileLayerOffline and savetiles
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Demonstrates how to create an instance of TileLayerOffline and use it with the savetiles function. Ensure TileLayerOffline is imported.
```typescript
const layer: TileLayerOffline = tileLayerOffline('https://...', {});
const control = savetiles(layer, {});
```
--------------------------------
### SaveStatus Event Handling
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Example of how to listen for save operation events and access the SaveStatus object. Logs the start and progress of a tile save operation.
```typescript
baseLayer.on('savestart', (status: SaveStatus) => {
console.log(`Saving ${status.lengthToBeSaved} tiles, ${status.storagesize} in storage`);
});
baseLayer.on('savetileend', (status: SaveStatus) => {
console.log(`${status.lengthSaved}/${status.lengthToBeSaved} saved`);
});
```
--------------------------------
### Watch Mode for Development
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Starts the build process in watch mode, automatically recompiling the library when source files change. This is useful during active development.
```bash
npm run watch
```
--------------------------------
### Create and Initialize ControlSaveTiles Instance
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Example of creating an offline-capable tile layer and then initializing the ControlSaveTiles with specific options. The control is then added to the map.
```typescript
import { tileLayerOffline, savetiles } from 'leaflet.offline';
const baseLayer = tileLayerOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
subdomains: 'abc',
});
const saveControl = savetiles(baseLayer, {
zoomlevels: [13, 14, 15],
maxZoom: 19,
saveText: 'Download',
rmText: 'Clear',
});
map.addLayer(baseLayer);
saveControl.addTo(map);
```
--------------------------------
### ControlSaveTiles getStorageSize Example
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Example of using the legacy getStorageSize method to retrieve the tile count and process it via a callback function.
```typescript
saveControl.getStorageSize((count) => {
console.log(`${count} tiles cached`);
});
```
--------------------------------
### Minimal Leaflet.offline Configuration
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Basic setup for leaflet.offline, initializing a tile layer and the save control. Ensure the layers and controls are added to the map.
```typescript
import { tileLayerOffline, savetiles } from 'leaflet.offline';
const layer = tileLayerOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {});
const control = savetiles(layer, {});
map.addLayer(layer);
control.addTo(map);
```
--------------------------------
### Multi-Layer Setup with Separate Controls
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Initialize multiple tile layers with leaflet.offline and create separate save controls for each. This allows users to manage caching for different map layers independently.
```typescript
const osmLayer = tileLayerOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {});
const wmtsLayer = tileLayerOffline(
'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
{}
);
const osmControl = savetiles(osmLayer, { saveText: 'OSM', rmText: 'Clear OSM' });
const wmtsControl = savetiles(wmtsLayer, { saveText: 'Imagery', rmText: 'Clear Imagery' });
map.addLayer(osmLayer);
osmControl.addTo(map);
wmtsControl.addTo(map);
```
--------------------------------
### Listen to Save Events
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Examples of how to listen to save progress events fired by the baseLayer. These events provide status updates during the tile saving process.
```typescript
baseLayer.on('savestart', (status) => {
console.log(`Starting to save ${status.lengthToBeSaved} tiles`);
});
```
```typescript
baseLayer.on('savetileend', (status) => {
const percent = Math.round((status.lengthSaved / status.lengthToBeSaved) * 100);
console.log(`Progress: ${percent}%`);
});
```
```typescript
baseLayer.on('saveend', (status) => {
console.log(`Done! ${status.storagesize} tiles now in storage`);
});
```
--------------------------------
### ControlSaveTiles setLayer Example
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Demonstrates how to create a ControlSaveTiles instance with one tile layer and then switch it to manage a different tile layer using the setLayer method.
```typescript
const layer1 = tileLayerOffline('https://...', {});
const layer2 = tileLayerOffline('https://...', {});
const control = savetiles(layer1, {});
// Switch to layer2
control.setLayer(layer2);
```
--------------------------------
### SaveStatus Event Handling Example
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Demonstrates how to use the SaveStatus object received from events like 'savetileend' to track and display the progress of a tile saving operation.
```typescript
baseLayer.on('savetileend', (status: SaveStatus) => {
const percent = Math.round((status.lengthSaved / status.lengthToBeSaved) * 100);
console.log(`Saving ${percent}% complete`);
console.log(`Total storage: ${status.storagesize} tiles`);
});
```
--------------------------------
### Test Storage Availability on App Initialization
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
Before relying on offline storage, test its availability using a simple operation like getting the storage length. This helps in gracefully degrading functionality if storage is unavailable.
```typescript
getStorageLength().catch(() => {
console.warn('Offline storage unavailable');
});
```
--------------------------------
### Get Storage Information
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Retrieves information about cached tiles for a specific tile layer URL template.
```APIDOC
## getStorageInfo(urlTemplate)
### Description
Lists tiles cached for a specific source URL template.
### Method
Function
### Parameters
- **urlTemplate** (string) - Required - The URL template of the tile source.
```
--------------------------------
### Generate Documentation
Source: https://github.com/allartk/leaflet.offline/blob/main/README.md
Command to generate API documentation for the project. This is useful for understanding the library's structure and available functions.
```bash
npm run-script docs
```
--------------------------------
### Get Storage Length
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Counts the total number of cached tiles.
```APIDOC
## getStorageLength()
### Description
Counts the total number of cached tiles.
```
--------------------------------
### Tile Layer with Retina/HiDPI Support
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Enable Retina or HiDPI support by including the {r} placeholder in the URL.
```typescript
tileLayerOffline('https://tile.openstreetmap.org/{z}/{x}/{y}{r}.png', {})
```
--------------------------------
### Get Cached Tile Blob
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Retrieves the Blob data for a cached tile using its key.
```APIDOC
## getBlobByKey(key)
### Description
Retrieves a cached tile blob by its key.
### Method
Function
### Parameters
- **key** (string) - Required - The unique key identifying the tile.
```
--------------------------------
### Documentation Directory Structure
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md
Illustrates the organization of documentation files within the project.
```tree
/workspace/home/output/
├── INDEX.md # Navigation & quick reference
├── README.md # Project overview & architecture
├── types.md # Type definitions
├── configuration.md # Configuration options & patterns
├── errors.md # Error handling & recovery
├── DOCUMENTATION_SUMMARY.md # This file
└── api-reference/
├── TileLayerOffline.md # Layer class API
├── ControlSaveTiles.md # Control class API
└── TileManager.md # Utility functions API
```
--------------------------------
### Catching Network Errors in downloadTile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
Demonstrates how to use a try/catch block to handle errors when calling the `downloadTile` function. This is essential for implementing retry logic or notifying the user of download failures.
```typescript
import { downloadTile } from 'leaflet.offline';
try {
const blob = await downloadTile(tileUrl);
console.log(`Downloaded ${blob.size} bytes`);
} catch (err) {
console.error(`Failed to download tile: ${err.message}`);
// Handle: retry, skip tile, notify user, etc.
}
```
--------------------------------
### Import Leaflet.offline in script
Source: https://github.com/allartk/leaflet.offline/blob/main/README.md
Import the library into your JavaScript or TypeScript file after installation. This makes its functionality available for use.
```javascript
import 'leaflet.offline'
```
--------------------------------
### ControlSaveTiles Usage Example
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Shows how to instantiate and add the ControlSaveTiles instance to a Leaflet map. This is typically done using the savetiles() factory function.
```typescript
const control: ControlSaveTiles = savetiles(baseLayer, {});
control.addTo(map);
```
--------------------------------
### Download Tile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Fetches a single tile from its network URL.
```APIDOC
## downloadTile(url)
### Description
Fetches a tile from the network.
### Method
Function
### Parameters
- **url** (string) - Required - The URL of the tile to download.
```
--------------------------------
### Configuration Options
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md
Details on configuration options for controlling plugin behavior.
```APIDOC
## Configuration Options
### `SaveTileOptions`
Details on all `SaveTileOptions`, including their default values and descriptions.
### `TileLayerOptions` Integration
Information on how `TileLayerOptions` integrate with offline capabilities.
### Environment Patterns and Advanced Scenarios
Guidance on configuring the plugin for various environments and advanced use cases.
```
--------------------------------
### Download a Single Tile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Fetches a tile image from the network. Use this before saving a tile to local storage. Throws an error if the fetch fails or the response is not OK.
```typescript
import { downloadTile, saveTile } from 'leaflet.offline';
const tileInfo = {
key: 'my-key',
url: 'https://tile.openstreetmap.org/15/16384/10924.png',
// ... other TileInfo fields
};
try {
const blob = await downloadTile(tileInfo.url);
console.log(`Downloaded ${blob.size} bytes`);
// Save to storage
await saveTile(tileInfo, blob);
} catch (err) {
console.error(`Failed to download tile: ${err.message}`);
}
```
--------------------------------
### Configure Tile Download Scope
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Use `saveWhatYouSee` to determine the scope of tile downloads. Set to `true` to download all zoom levels from current to `maxZoom`, or `false` to download only specified levels or the current level.
```typescript
// Save current zoom + all higher zooms up to 18
const control1 = savetiles(baseLayer, {
saveWhatYouSee: true,
maxZoom: 18,
});
// Save only specific zoom levels
const control2 = savetiles(baseLayer, {
saveWhatYouSee: false,
zoomlevels: [13, 15, 17],
});
// Save only current zoom
const control3 = savetiles(baseLayer, {
saveWhatYouSee: false,
});
```
--------------------------------
### Preventing Minimum Zoom Error
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
This example shows how to catch and prevent the minimum zoom error by either disabling the save button or displaying a warning when the user zooms out below level 5.
```typescript
import { savetiles } from 'leaflet.offline';
const control = savetiles(baseLayer, {
saveWhatYouSee: true,
maxZoom: 19,
});
// Prevent user from triggering the error
map.on('zoomend', () => {
const currentZoom = map.getZoom();
if (currentZoom < 5) {
console.warn('Zoom in to level 5+ to save tiles');
// Disable button or show warning
}
});
```
--------------------------------
### Get Total Cached Tile Count
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Counts the total number of cached tiles across all tile providers. Use this to monitor storage usage. Errors from IndexedDB may occur.
```typescript
import { getStorageLength } from 'leaflet.offline';
getStorageLength().then((count) => {
console.log(`${count} tiles cached`);
});
```
--------------------------------
### User-Controlled Caching with Custom Text and Confirmations
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Configure the save control with custom text for download and removal actions. Implement confirmation dialogs for both saving and removing tiles to prevent accidental data loss.
```typescript
const control = savetiles(baseLayer, {
saveText: 'Download Tiles',
rmText: 'Clear Cache',
zoomlevels: [13, 14, 15],
confirm: (status, success) => {
const msg = `Cache ${status._tilesforSave.length} tiles?`;
if (window.confirm(msg)) success();
},
confirmRemoval: (status, success) => {
if (window.confirm('Clear all cached tiles?')) success();
},
});
```
--------------------------------
### Stamen Toner Tile Layer with Subdomains
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Configure a Stamen Toner tile layer using multiple subdomains specified in an array.
```typescript
tileLayerOffline('https://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
subdomains: ['a', 'b', 'c', 'd'],
})
```
--------------------------------
### Get Tile Image Source (Cached or Network)
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Determines the source for a tile's image, prioritizing cached storage. If the tile is cached, it returns a blob object URL; otherwise, it returns the original network URL. This is used internally by TileLayerOffline.
```typescript
async function getTileImageSource(key: string, url: string): Promise
```
```typescript
import { getTileImageSource } from 'leaflet.offline';
const key = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png/15/16384/10924';
const url = 'https://a.tile.openstreetmap.org/15/16384/10924.png';
const src = await getTileImageSource(key, url);
// If cached: returns a blob URL like "blob:https://example.com/"
// If not cached: returns the original URL
```
--------------------------------
### Bulk Tile Download and Caching
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Downloads and caches multiple tiles in parallel. Ensure you have an array of TileInfo objects.
```typescript
import { downloadTile, saveTile } from 'leaflet.offline';
const tiles = [ /* array of TileInfo */ ];
await Promise.all(tiles.map(async (tile) => {
try {
const blob = await downloadTile(tile.url);
await saveTile(tile, blob);
} catch (err) {
console.error(`Failed to cache ${tile.key}: ${err.message}`);
}
}));
```
--------------------------------
### Data Flow for Offline Tile Caching
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Illustrates the sequence of operations when saving tiles for offline use and when serving cached tiles.
```text
User clicks save button
↓
ControlSaveTiles calculates tiles in view/bounds
↓
TileManager.downloadTile() fetches each tile
↓
TileManager.saveTile() stores blob in IndexedDB
↓
Events fire on TileLayerOffline for progress
↓
Tiles now available offline
---
User pans/zooms map
↓
TileLayerOffline.createTile() for new coords
↓
getTileImageSource() checks IndexedDB
↓
Serve cached blob URL or network URL
↓
Tile displays
```
--------------------------------
### Standard OSM Tile Layer
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Use the standard XYZ placeholders for basic tile layer configuration.
```typescript
tileLayerOffline('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {})
```
--------------------------------
### Constructor
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Initializes a new instance of the ControlSaveTiles class. It takes a TileLayerOffline instance and optional configuration options.
```APIDOC
## Constructor
Initializes a new instance of the ControlSaveTiles class.
### Parameters
* **baseLayer** (TileLayerOffline) - Required - The tile layer instance to control.
* **options** (Partial) - Required - Partial options; missing values use defaults.
### Default Options
```json
{
"position": "topleft",
"saveText": "+",
"rmText": "-",
"maxZoom": 19,
"saveWhatYouSee": false,
"bounds": null,
"confirm": null,
"confirmRemoval": null,
"parallel": 50,
"zoomlevels": undefined,
"alwaysDownload": true
}
```
```
--------------------------------
### getStorageSize(callback)
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Fetches the tile count and invokes a callback with the result. This is a legacy method; prefer `setStorageSize()` for modern async/await usage.
```APIDOC
## getStorageSize(callback)
Fetches the tile count and invokes a callback with the result. Legacy method; prefer `setStorageSize()` for async/await.
### Method
```typescript
getStorageSize(callback: Function): void
```
### Parameters
* **callback** (Function) - Required - Called with the tile count as argument.
### Example
```typescript
saveControl.getStorageSize((count) => {
console.log(`${count} tiles cached`);
});
```
```
--------------------------------
### Open Tile Database
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Opens or creates the IndexedDB database for tile storage. This is typically called automatically on first use.
```typescript
function openTilesDataBase(): Promise
```
--------------------------------
### Download Tile Function
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
This function fetches a tile from a given URL. It throws an error if the network request fails, indicating issues like tile not found, server errors, or network unreachability. Wrap this in a try/catch block to handle potential network failures.
```typescript
export async function downloadTile(tileUrl: string): Promise {
const response = await fetch(tileUrl);
if (!response.ok) {
throw new Error(`Request failed with status ${response.statusText}`);
}
return response.blob();
}
```
--------------------------------
### Control Tile Re-download Behavior
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Set `alwaysDownload` to `true` to force re-download of all tiles, even if they exist in storage. Set to `false` (default) to skip existing tiles and save bandwidth.
```typescript
// Only download new/missing tiles
const control = savetiles(baseLayer, {
alwaysDownload: false,
});
// Always re-download (useful for periodic cache refreshes)
const control2 = savetiles(baseLayer, {
alwaysDownload: true,
});
```
--------------------------------
### Tile Layer with Custom Placeholder
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Utilize custom placeholders in the URL, providing their values through the options object.
```typescript
tileLayerOffline('https://server.com/{l}/{z}/{x}/{y}.png', {
l: 'my-layer',
})
```
--------------------------------
### Import TileManager Utilities
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Imports all necessary functions and types from the leaflet.offline library for tile management.
```typescript
import {
getStorageInfo,
getStorageLength,
getStoredTilesAsJson,
downloadTile,
saveTile,
removeTile,
truncate,
hasTile,
getBlobByKey,
getTilePoints,
getTileUrl,
getTileImageSource,
TileInfo,
StoredTile,
} from 'leaflet.offline';
```
--------------------------------
### Monitor Tile Loading Progress
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
Listen for 'loadtileend' events to confirm all tiles have been loaded successfully. This helps in identifying if the loading process completed as expected.
```typescript
baseLayer.on('loadtileend', (status: SaveStatus) => {
if (status.lengthLoaded > 0 && status.lengthLoaded === status.lengthToBeSaved) {
console.log('All tiles loaded');
}
});
```
--------------------------------
### downloadTile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Fetches a tile image from the network using its URL. Returns the image data as a Blob.
```APIDOC
## downloadTile
### Description
Fetches a tile image from the network.
### Method
`async function downloadTile(tileUrl: string): Promise`
### Parameters
#### Path Parameters
- **tileUrl** (string) - Required - Full tile URL to fetch
### Returns
`Promise` — Image data (usually JPEG or PNG).
### Throws
Error if the fetch fails (network error, 404, etc.) or the response is not OK.
### Example
```typescript
import { downloadTile, saveTile } from 'leaflet.offline';
const tileInfo = {
key: 'my-key',
url: 'https://tile.openstreetmap.org/15/16384/10924.png',
// ... other TileInfo fields
};
try {
const blob = await downloadTile(tileInfo.url);
console.log(`Downloaded ${blob.size} bytes`);
// Save to storage
await saveTile(tileInfo, blob);
} catch (err) {
console.error(`Failed to download tile: ${err.message}`);
}
```
```
--------------------------------
### Generate API Documentation
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Generates the API documentation for the Leaflet.Offline library. This command is useful for developers who need to understand the library's public API.
```bash
npm run docs:build
```
--------------------------------
### Configure Concurrent Download Limit
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Adjust the `parallel` option to control the maximum number of tiles downloaded simultaneously. Higher values can speed up downloads but may strain network resources or trigger server rate limits.
```typescript
const control = savetiles(baseLayer, {
parallel: 10, // Conservative: 10 simultaneous downloads
});
const control2 = savetiles(baseLayer, {
parallel: 100, // Aggressive: 100 simultaneous downloads
});
```
--------------------------------
### Type-Only Imports for leaflet.offline
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Demonstrates the recommended way to import types from leaflet.offline without importing any values. This improves tree-shaking.
```typescript
import type { TileInfo, SaveStatus, SaveTileOptions } from 'leaflet.offline';
```
--------------------------------
### Integration Notes
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileLayerOffline.md
Key considerations and methods for integrating TileLayerOffline into your application, including pairing with tile sources, fallback mechanisms, and programmatic control.
```APIDOC
## Integration Notes
- `TileLayerOffline` must be paired with a tile source (URL template) that supports the `{z}/{x}/{y}` or similar coordinate system.
- When a tile is not in storage and offline, the layer falls back to the original URL (which will fail if offline).
- Use `ControlSaveTiles` to manage tile downloads and storage programmatically.
- For advanced use, call `getTileUrls()` directly to get tiles for a custom bounds/zoom, then use `TileManager` functions (`downloadTile`, `saveTile`) to store them.
```
--------------------------------
### Tile Layer with Subdomains
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Configure tile layers to use subdomains by providing a string of characters.
```typescript
tileLayerOffline('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
subdomains: 'abc',
})
```
--------------------------------
### Import SaveTileOptions Type
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Import the SaveTileOptions interface for configuring tile saving controls.
```typescript
import type { SaveTileOptions } from 'leaflet.offline';
```
--------------------------------
### Manual Tile Management with Leaflet.Offline
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Provides functions for manually downloading, saving, and removing individual tiles. This allows for fine-grained control over the offline tile cache.
```typescript
import {
downloadTile,
saveTile,
removeTile,
getStorageLength
} from 'leaflet.offline';
// Manually download and cache a tile
const blob = await downloadTile(
'https://tile.openstreetmap.org/15/16384/10924.png'
);
await saveTile({
key: '...',
url: '...',
urlTemplate: '...',
x: 16384,
y: 10924,
z: 15,
createdAt: Date.now(),
}, blob);
// Check storage
const count = await getStorageLength();
console.log(`${count} tiles cached`);
// Remove old tile
await removeTile('tile-key');
```
--------------------------------
### Leaflet Factory Method for ControlSaveTiles
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Demonstrates how to use the Leaflet factory method to create a ControlSaveTiles instance when using the global L object.
```javascript
// When using window.L
L.control.savetiles(baseLayer, options)
```
--------------------------------
### Implement Quota Management for Storage
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
Monitor the amount of cached data and implement a strategy to clear old tiles when the storage approaches its limit. This prevents 'QuotaExceededError'.
```typescript
const count = await getStorageLength();
if (count > 10000) {
await truncate(); // Clear and re-cache
}
```
--------------------------------
### Generate Tile URL
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Renders a URL template by substituting placeholders with provided tile coordinates and metadata. Supports placeholders like {z}, {x}, {y}, {s}, and {r}.
```typescript
function getTileUrl(urlTemplate: string, data: any): string
```
```typescript
import { getTileUrl } from 'leaflet.offline';
const url = getTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}{r}.png', {
z: 15,
x: 16384,
y: 10924,
s: 'a',
r: '', // no retina
});
console.log(url);
// Output: https://a.tile.openstreetmap.org/15/16384/10924.png
```
--------------------------------
### openTilesDataBase
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Opens or creates the IndexedDB database for tile storage. This function is typically called automatically on first use and usually does not require direct invocation in application code.
```APIDOC
## openTilesDataBase
### Description
Opens or creates the IndexedDB database for tile storage. Called automatically on first use; typically not needed in application code.
### Method
`function`
### Returns
`Promise` — A promise resolving to the IDB database instance.
### Example
```typescript
import { openTilesDataBase } from 'leaflet.offline';
const db = await openTilesDataBase();
const allKeys = await db.getAllKeys('tileStore');
console.log(`${allKeys.length} tiles in storage`);
```
```
--------------------------------
### ControlSaveTiles Configuration
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
The ControlSaveTiles constructor enables saving tiles to local storage with various configuration options.
```APIDOC
## ControlSaveTiles
### Description
Provides functionality to save map tiles for offline use and manage the cache. It accepts various options to customize the saving process.
### Signature
```typescript
savetiles(baseLayer: TileLayerOffline, options: Partial)
```
### Parameters
#### Options
- **zoomlevels** (number[]) - Optional - An array of specific zoom levels to cache.
- **saveWhatYouSee** (boolean) - Optional - If true, caches the current zoom level and higher; otherwise, caches specified zoom levels. Defaults to false.
- **maxZoom** (number) - Optional - The maximum zoom level to cache when `saveWhatYouSee` is true.
- **parallel** (number) - Optional - The number of concurrent downloads allowed for saving tiles.
- **alwaysDownload** (boolean) - Optional - If true, skips checking the cache and always downloads tiles. Defaults to false.
- **confirm** (function) - Optional - A callback function to confirm the saving of tiles. Receives status and a callback function.
- **confirmRemoval** (function) - Optional - A callback function to confirm the removal of cached tiles. Receives status and a callback function.
```
--------------------------------
### Catching QuotaExceededError when Saving a Tile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
Demonstrates how to use a try-catch block to handle potential errors when saving a tile, specifically checking for 'QuotaExceededError' and logging appropriate messages.
```typescript
import { saveTile } from 'leaflet.offline';
const tile = { /* TileInfo */ };
const blob = new Blob([/* image data */]);
try {
await saveTile(tile, blob);
console.log(`Saved ${tile.key}`);
} catch (err) {
if (err.name === 'QuotaExceededError') {
console.error('Storage is full; consider clearing old tiles');
} else {
console.error(`Database error: ${err.message}`);
}
}
```
--------------------------------
### TileLayerOffline Configuration
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
The TileLayerOffline constructor allows for custom options to control tile loading and display behavior.
```APIDOC
## TileLayerOffline
### Description
Initializes a TileLayer with offline capabilities, allowing for custom options to manage tile loading and display.
### Signature
```typescript
tileLayerOffline(url: string, options: TileLayerOptions)
```
### Parameters
#### Options
- **minZoom** (number) - Optional - Minimum zoom level to display tiles.
- **maxZoom** (number) - Optional - Maximum zoom level to display tiles.
- **attribution** (string) - Optional - HTML attribution string to display with the map.
- **subdomains** (string) - Optional - Subdomains to use for load balancing tile requests.
- **crossOrigin** (boolean) - Optional - Whether to use CORS for tile images.
```
--------------------------------
### Save a Downloaded Tile Blob
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Saves a downloaded tile blob to IndexedDB storage. Requires a TileInfo object with a `key` field. Errors from IndexedDB, such as quota exceeded, may occur.
```typescript
import { saveTile } from 'leaflet.offline';
const tile: TileInfo = { /* ... */ };
const blob = new Blob([/* image data */], { type: 'image/png' });
await saveTile(tile, blob);
console.log(`Tile ${tile.key} saved`);
```
--------------------------------
### getTileUrl
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Renders a URL template with tile coordinates and metadata, producing a fully formed URL for fetching tile images.
```APIDOC
## getTileUrl
### Description
Renders a URL template with tile coordinates and metadata.
### Method
`function getTileUrl(urlTemplate: string, data: any): string`
### Parameters
#### Path Parameters
- **urlTemplate** (string) - Required - URL with placeholders (e.g., `{z}`, `{x}`, `{y}`, `{s}`, `{r}`)
- **data** (any) - Required - Object with coordinate and option fields
### Supported Placeholders
| Placeholder | Source | Example |
|-------------|--------|---------|
| `{z}` | data.z | 15 |
| `{x}` | data.x | 16384 |
| `{y}` | data.y | 10924 |
| `{s}` | data.s (subdomain) | 'a', 'b', or 'c' |
| `{r}` | '@2x' if retina, else '' | '@2x' or '' |
### Returns
- **string** - Fully rendered URL ready for fetch.
### Example
```typescript
import { getTileUrl } from 'leaflet.offline';
const url = getTileUrl('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}{r}.png', {
z: 15,
x: 16384,
y: 10924,
s: 'a',
r: '', // no retina
});
console.log(url);
// Output: https://a.tile.openstreetmap.org/15/16384/10924.png
```
```
--------------------------------
### Import TileInfo Type
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/types.md
Demonstrates how to import the TileInfo type from the leaflet.offline library for use in your TypeScript projects.
```typescript
import type { TileInfo } from 'leaflet.offline';
```
--------------------------------
### Error Conditions
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md
Documentation on potential errors and how to handle them.
```APIDOC
## Error Conditions
- Network failures and recovery strategies.
- Storage quota and access issues.
- Validation errors.
- CORS restrictions.
- Handling of silent failures.
```
--------------------------------
### Retrieve Tile Blob by Key
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Fetches the image blob for a cached tile using its key. Returns the blob if found, otherwise undefined. Errors from IndexedDB may be thrown.
```typescript
async function getBlobByKey(key: string): Promise
```
```typescript
import { getBlobByKey } from 'leaflet.offline';
const blob = await getBlobByKey('my-tile-key');
if (blob) {
const url = URL.createObjectURL(blob);
console.log(`Blob object URL: ${url}`);
}
```
--------------------------------
### Advanced Use: Accessing Tile Count
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/TileManager.md
Demonstrates advanced usage by opening the tile database and retrieving the total number of stored tiles.
```typescript
import { openTilesDataBase } from 'leaflet.offline';
const db = await openTilesDataBase();
const allKeys = await db.getAllKeys('tileStore');
console.log(`${allKeys.length} tiles in storage`);
```
--------------------------------
### Minimum Zoom Check in _calculateTiles()
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
This error is thrown when attempting to save tiles at zoom levels below 5 while `saveWhatYouSee: true`. It prevents downloading tiles for the entire world.
```typescript
_calculateTiles() {
let minZoom = 5;
if (this.options.saveWhatYouSee) {
const currentZoom = this._map.getZoom();
if (currentZoom < minZoom) {
throw new Error(`It's not possible to save with zoom below level ${minZoom}.`);
}
// ...
}
}
```
--------------------------------
### Check Offline Storage Availability
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
This function attempts to open a database to verify if offline storage is accessible. It catches errors and logs a warning if storage is unavailable, returning false.
```typescript
async function canUseOfflineStorage(): Promise {
try {
const db = await openTilesDataBase();
return !!db;
} catch (err) {
console.warn('Offline storage unavailable:', err.message);
return false;
}
}
if (await canUseOfflineStorage()) {
// Show save controls
} else {
// Hide save controls or show message
}
```
--------------------------------
### Instantiate TileLayerOffline with Custom Options
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/configuration.md
Use this snippet to create a TileLayerOffline instance with specific attribution, subdomains, zoom levels, and cross-origin settings. Ensure Leaflet is imported and a map object is available.
```typescript
import { tileLayerOffline } from 'leaflet.offline';
const baseLayer = tileLayerOffline(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: 'Map data © OpenStreetMap contributors',
subdomains: ['a', 'b', 'c'],
minZoom: 5,
maxZoom: 19,
crossOrigin: true,
}
);
map.addLayer(baseLayer);
```
--------------------------------
### Create Save/Clear Control
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Use `savetiles` to create a control for managing tile saving and clearing. This function is also available globally as `L.control.savetiles` after importing the library.
```javascript
L.control.savetiles(layer, options)
```
--------------------------------
### ControlSaveTiles Default Options
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
These are the default configuration options applied if not explicitly provided during the ControlSaveTiles instantiation. They cover UI text, zoom limits, download behavior, and more.
```typescript
{
position: 'topleft',
saveText: '+',
rmText: '-',
maxZoom: 19,
saveWhatYouSee: false,
bounds: null,
confirm: null,
confirmRemoval: null,
parallel: 50,
zoomlevels: undefined,
alwaysDownload: true,
}
```
--------------------------------
### Exported Functions
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/DOCUMENTATION_SUMMARY.md
Core functions for managing offline tiles, including fetching, saving, removing, and querying tile data.
```APIDOC
## Exported Functions
### `tileLayerOffline()`
Factory for creating an offline tile layer.
### `savetiles()`
Factory for creating a control to save and clear tiles.
### `getStorageLength()`
Counts the number of cached tiles.
### `getStorageInfo()`
Lists cached tiles by source.
### `downloadTile()`
Fetches a tile from the network.
### `saveTile()`
Stores a tile in IndexedDB.
### `removeTile()`
Deletes a single cached tile.
### `truncate()`
Clears all cached tiles.
### `hasTile()`
Checks if a specific tile exists in the cache.
### `getBlobByKey()`
Retrieves a tile's blob data using its key.
### `getTileUrl()`
Renders a tile URL from a template.
### `getTilePoints()`
Gets the tile coordinates.
### `getStoredTilesAsJson()`
Exports stored tiles as a GeoJSON object.
```
--------------------------------
### Run Tests for Leaflet.Offline
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Executes the test suite for the Leaflet.Offline library. This command is used to verify the correctness of the library's functionality.
```bash
npm test
```
--------------------------------
### Save Tile
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Stores a fetched tile in the IndexedDB cache.
```APIDOC
## saveTile(tileInfo, blob)
### Description
Stores a tile in IndexedDB.
### Method
Function
### Parameters
- **tileInfo** (TileInfo) - Required - Metadata for the tile.
- **blob** (Blob) - Required - The tile image data as a Blob.
```
--------------------------------
### Check Tile Existence
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/README.md
Checks if a tile with the given key exists in the cache.
```APIDOC
## hasTile(key)
### Description
Checks if a tile exists in the cache.
### Method
Function
### Parameters
- **key** (string) - Required - The unique key identifying the tile.
```
--------------------------------
### Wrap Network Calls in Try/Catch
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/errors.md
Always wrap network calls in a try/catch block to handle potential errors gracefully. This is crucial for operations like downloading tiles.
```typescript
try {
const blob = await downloadTile(url);
} catch (err) {
// Handle gracefully
}
```
--------------------------------
### setStorageSize()
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/api-reference/ControlSaveTiles.md
Queries the tile storage to count cached tiles and updates the control's status. This method is asynchronous and returns a Promise.
```APIDOC
## setStorageSize()
Queries the tile storage to count cached tiles and updates the control's status. Returns a promise resolving to the tile count.
### Method
```typescript
setStorageSize(): Promise
```
### Returns
* `Promise` - Resolves to the number of tiles in storage.
### Throws
Silently catches errors and returns 0.
### Example
```typescript
const saveControl = savetiles(baseLayer, {});
saveControl.setStorageSize().then((count) => {
console.log(`${count} tiles cached`);
});
```
```
--------------------------------
### Import Core Functions from Leaflet.offline
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/INDEX.md
Import all necessary functions for leaflet.offline functionality.
```typescript
import {
tileLayerOffline,
savetiles,
getStorageInfo,
downloadTile,
saveTile,
truncate,
} from 'leaflet.offline';
```
--------------------------------
### Monitor Tile Saving Progress
Source: https://github.com/allartk/leaflet.offline/blob/main/_autodocs/INDEX.md
Listen for the 'savetileend' event to track the progress of tile saving operations.
```typescript
layer.on('savetileend', (status) => {
console.log(`${status.lengthSaved}/${status.lengthToBeSaved} saved`);
});
```