A comprehensive Svelte SDK for the OpenCage Geocoding API with reactive stores, actions, and pre-built components. Built specifically for Svelte and SvelteKit applications with full TypeScript support, SSR compatibility, and optimal bundle size.
# npm
npm install @digiphilo/opencage-svelte
# yarn
yarn add @digiphilo/opencage-svelte
# pnpm
pnpm add @digiphilo/opencage-svelte
import { initializeOpenCage } from '@opencage/svelte-sdk';
initializeOpenCage({
apiKey: 'YOUR_API_KEY_HERE',
cache: true,
timeout: 10000
});
<script>
import { GeocodingInput } from '@opencage/svelte-sdk';
function handleSelect(event) {
console.log('Selected address:', event.detail.result);
}
</script>
<GeocodingInput
placeholder="Enter an address..."
on:select={handleSelect}
/>
<script>
import { AddressDisplay } from '@opencage/svelte-sdk';
export let result;
</script>
<AddressDisplay
{result}
showConfidence={true}
showCoordinates={true}
clickable={true}
/>
The SDK provides reactive Svelte stores for managing geocoding state:
import {
geocodingStore,
isGeocoding,
geocodingError,
performGeocode
} from '@opencage/svelte-sdk';
// Perform geocoding
const results = await performGeocode('Berlin, Germany');
// Subscribe to state changes
$: if ($isGeocoding) {
console.log('Geocoding in progress...');
}
$: if ($geocodingError) {
console.error('Geocoding error:', $geocodingError);
}
Svelte actions provide declarative DOM integration:
<script>
import { geocodeAction } from '@opencage/svelte-sdk';
</script>
<!-- Automatic geocoding on input -->
<input
use:geocodeAction={{
debounceMs: 300,
minLength: 3,
onResult: (results) => console.log(results)
}}
placeholder="Type an address..."
/>
Pre-built components with full customization:
<script>
import {
GeocodingInput,
AddressDisplay,
BatchGeocoder
} from '@opencage/svelte-sdk';
</script>
<!-- Geocoding input with suggestions -->
<GeocodingInput
showSuggestions={true}
maxSuggestions={5}
debounceMs={300}
on:select={handleSelect}
/>
<!-- Address display with metadata -->
<AddressDisplay
{result}
format="components"
showConfidence={true}
showCoordinates={true}
coordinatesPrecision={6}
/>
<!-- Batch processing -->
<BatchGeocoder
queries={['Berlin', 'Munich', 'Hamburg']}
concurrency={5}
showProgress={true}
on:complete={handleBatchComplete}
/>
Use the Svelte context for dependency injection:
<script>
import { createOpenCageContext } from '@opencage/svelte-sdk';
// In your root component
createOpenCageContext({
apiKey: 'YOUR_API_KEY_HERE',
cache: true
});
</script>
<!-- Child components can now access the context -->
<ChildComponent />
Server-side geocoding in load functions:
// src/routes/+page.server.ts
import type { PageServerLoad } from './$types';
import { geocode } from '@opencage/svelte-sdk';
export const load: PageServerLoad = async ({ url }) => {
const query = url.searchParams.get('address');
if (query) {
try {
const response = await geocode(query, {
apiKey: process.env.OPENCAGE_API_KEY,
cache: false // Disable cache for server-side
});
return {
results: response.results
};
} catch (error) {
return {
error: error.message
};
}
}
return {};
};
import { performGeocode } from '@opencage/svelte-sdk';
const results = await performGeocode('Berlin', {
language: 'de',
countrycode: 'de',
bounds: [13.0824, 52.3382, 13.7606, 52.6755], // Berlin bounds
proximity: [52.5170365, 13.3888599], // Center of Berlin
limit: 10,
min_confidence: 7,
no_annotations: false
});
<script>
import { performBatchGeocode } from '@opencage/svelte-sdk';
async function processBatch() {
const queries = ['Berlin', 'Munich', 'Hamburg'];
const results = await performBatchGeocode(
queries,
{ language: 'en' }, // Geocoding options
5, // Concurrency
(progress) => {
console.log(`${progress.completed}/${progress.total} (${progress.percentage}%)`);
}
);
console.log('Batch results:', results);
}
</script>
A smart input component with autocomplete and suggestion support.
| Prop | Type | Default | Description |
|---|---|---|---|
value |
string |
'' |
Input value |
placeholder |
string |
'Enter an address...' |
Placeholder text |
disabled |
boolean |
false |
Disable the input |
showSuggestions |
boolean |
true |
Show autocomplete suggestions |
maxSuggestions |
number |
5 |
Maximum suggestions to show |
debounceMs |
number |
300 |
Debounce delay in milliseconds |
minLength |
number |
3 |
Minimum input length to start geocoding |
geocodingOptions |
GeocodingOptions |
{} |
OpenCage API options |
| Event | Detail | Description |
|---|---|---|
input |
{ value: string } |
Input value changed |
result |
{ results: OpenCageResult[], query: string } |
Geocoding results received |
select |
{ result: OpenCageResult, index: number } |
Suggestion selected |
error |
{ error: string, query: string } |
Geocoding error occurred |
| Slot | Props | Description |
|---|---|---|
loading |
- | Custom loading indicator |
error |
{ error } |
Custom error display |
suggestion |
{ result, index } |
Custom suggestion item |
no-results |
- | Custom no results message |
A component for displaying geocoding results with metadata.
| Prop | Type | Default | Description |
|---|---|---|---|
result |
OpenCageResult |
- | Required. The geocoding result to display |
format |
'full' | 'short' | 'components' | 'custom' |
'full' |
Display format |
showConfidence |
boolean |
false |
Show confidence score |
showCoordinates |
boolean |
false |
Show coordinates |
coordinatesPrecision |
number |
6 |
Decimal places for coordinates |
clickable |
boolean |
false |
Make the component clickable |
| Event | Detail | Description |
|---|---|---|
click |
{ result: OpenCageResult } |
Component clicked (if clickable) |
copyCoordinates |
{ coordinates: string } |
Coordinates copied to clipboard |
copyAddress |
{ address: string } |
Address copied to clipboard |
A component for processing multiple geocoding requests with progress tracking.
| Prop | Type | Default | Description |
|---|---|---|---|
queries |
string[] |
[] |
Array of address queries |
concurrency |
number |
5 |
Number of concurrent requests |
showProgress |
boolean |
true |
Show progress indicator |
showResults |
boolean |
true |
Show results list |
allowRetry |
boolean |
true |
Allow retrying failed requests |
| Event | Detail | Description |
|---|---|---|
start |
{ queries: string[] } |
Batch processing started |
progress |
BatchProgress |
Progress update |
complete |
{ results, totalTime, summary } |
Batch processing completed |
error |
{ error: string } |
Batch processing error |
interface OpenCageConfig {
apiKey: string; // Your OpenCage API key
baseUrl?: string; // API base URL (default: official API)
timeout?: number; // Request timeout in ms (default: 10000)
retries?: number; // Retry attempts (default: 3)
cache?: boolean; // Enable caching (default: true)
cacheSize?: number; // Max cache entries (default: 100)
cacheTTL?: number; // Cache TTL in ms (default: 300000)
rateLimitBuffer?: number; // Rate limit buffer (default: 10)
}
interface GeocodingOptions {
language?: string; // Response language (ISO 639-1)
countrycode?: string | string[]; // Restrict to country codes
bounds?: [number, number, number, number]; // Bounding box
proximity?: [number, number]; // Proximity point [lat, lng]
limit?: number; // Maximum results (default: 10)
min_confidence?: number; // Minimum confidence (1-10)
no_annotations?: boolean; // Exclude annotations
no_dedupe?: boolean; // Disable deduplication
no_record?: boolean; // Don't record request
abbrv?: boolean; // Abbreviate results
add_request?: boolean; // Include request in response
}
The SDK includes comprehensive unit tests:
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run coverage
# Run tests in UI mode
npm run test:ui
import { render, screen } from '@testing-library/svelte';
import { configStore } from '@opencage/svelte-sdk';
import YourComponent from './YourComponent.svelte';
test('should render geocoding input', () => {
// Initialize SDK for testing
configStore.init({
apiKey: 'test-api-key-32-characters-long'
});
render(YourComponent);
const input = screen.getByPlaceholderText('Enter an address...');
expect(input).toBeInTheDocument();
});
// vite.config.js
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default defineConfig({
plugins: [svelte()],
optimizeDeps: {
include: ['@opencage/svelte-sdk']
}
});
// svelte.config.js
import adapter from '@sveltejs/adapter-auto';
const config = {
kit: {
adapter: adapter(),
vite: {
optimizeDeps: {
include: ['@opencage/svelte-sdk']
}
}
}
};
export default config;
# .env
VITE_OPENCAGE_API_KEY=your-api-key-here
OPENCAGE_API_KEY=your-server-side-api-key
// Usage in component
import { browser } from '$app/environment';
if (browser) {
initializeOpenCage({
apiKey: import.meta.env.VITE_OPENCAGE_API_KEY
});
}
// Secure server-side geocoding
export const load: PageServerLoad = async ({ request }) => {
const apiKey = process.env.OPENCAGE_API_KEY;
if (!apiKey) {
throw error(500, 'API key not configured');
}
// Process geocoding server-side
};
// Import only what you need
import { performGeocode } from '@opencage/svelte-sdk/stores';
import { GeocodingInput } from '@opencage/svelte-sdk/components';
// Instead of importing everything
import { performGeocode, GeocodingInput } from '@opencage/svelte-sdk';
// Configure caching
initializeOpenCage({
apiKey: 'your-key',
cache: true,
cacheSize: 200, // Increase cache size
cacheTTL: 600000, // 10 minutes
});
// Manual cache management
import { clearCache, getCacheStats } from '@opencage/svelte-sdk';
console.log('Cache stats:', getCacheStats());
clearCache(); // Clear when needed
// Optimal debouncing for different use cases
const searchInput = {
debounceMs: 300, // Good for search-as-you-type
minLength: 3 // Avoid short queries
};
const addressForm = {
debounceMs: 500, // Less aggressive for forms
minLength: 5 // More specific queries
};
We welcome contributions! Please see our Contributing Guide for details.
git clone https://github.com/opencagedata/svelte-sdk.git
cd svelte-sdk
npm install
npm run dev
cd examples/sveltekit-app
npm install
npm run dev
MIT License
Copyright (c) 2025 Rome Stone
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Author: Rome Stone