opencage-svelte Svelte Themes

Opencage Svelte

OpenCage Geocoding API SDK for svelte

OpenCage Svelte SDK

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.

๐Ÿš€ Features

  • Reactive Stores: Svelte stores for state management and real-time updates
  • Svelte Actions: DOM actions for input binding and geocoding automation
  • Pre-built Components: Ready-to-use UI components with full customization
  • TypeScript: Complete type definitions and IntelliSense support
  • SSR Compatible: Works with SvelteKit server-side rendering
  • Tree Shakeable: Import only what you need for minimal bundle size
  • Caching: Smart caching with configurable TTL and size limits
  • Batch Processing: Process multiple geocoding requests with progress tracking
  • Rate Limiting: Built-in rate limit handling and retry logic
  • Error Handling: Comprehensive error types and handling
  • Accessibility: WCAG compliant components with proper ARIA attributes

๐Ÿ“ฆ Installation

# npm
npm install @digiphilo/opencage-svelte

# yarn
yarn add @digiphilo/opencage-svelte

# pnpm
pnpm add @digiphilo/opencage-svelte

๐Ÿƒ Quick Start

1. Initialize the SDK

import { initializeOpenCage } from '@opencage/svelte-sdk';

initializeOpenCage({
  apiKey: 'YOUR_API_KEY_HERE',
  cache: true,
  timeout: 10000
});

2. Use the Geocoding Input Component

<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}
/>

3. Display Results

<script>
  import { AddressDisplay } from '@opencage/svelte-sdk';
  
  export let result;
</script>

<AddressDisplay
  {result}
  showConfidence={true}
  showCoordinates={true}
  clickable={true}
/>

๐ŸŽฏ Core Concepts

Stores

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);
}

Actions

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..."
/>

Components

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}
/>

๐Ÿ› ๏ธ Advanced Usage

Context API

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 />

SSR with SvelteKit

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 {};
};

Custom Geocoding Options

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
});

Batch Processing with Progress

<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>

๐ŸŽจ Component API

GeocodingInput

A smart input component with autocomplete and suggestion support.

Props

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

Events

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

Slots

Slot Props Description
loading - Custom loading indicator
error { error } Custom error display
suggestion { result, index } Custom suggestion item
no-results - Custom no results message

AddressDisplay

A component for displaying geocoding results with metadata.

Props

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

Events

Event Detail Description
click { result: OpenCageResult } Component clicked (if clickable)
copyCoordinates { coordinates: string } Coordinates copied to clipboard
copyAddress { address: string } Address copied to clipboard

BatchGeocoder

A component for processing multiple geocoding requests with progress tracking.

Props

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

Events

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

๐Ÿ”ง Configuration

SDK Configuration

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)
}

Geocoding Options

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
}

๐Ÿงช Testing

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

Testing Your Components

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();
});

๐Ÿ“š Examples

Basic Vite/Rollup Setup

// vite.config.js
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';

export default defineConfig({
  plugins: [svelte()],
  optimizeDeps: {
    include: ['@opencage/svelte-sdk']
  }
});

SvelteKit Setup

// svelte.config.js
import adapter from '@sveltejs/adapter-auto';

const config = {
  kit: {
    adapter: adapter(),
    vite: {
      optimizeDeps: {
        include: ['@opencage/svelte-sdk']
      }
    }
  }
};

export default config;

Environment Variables

# .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
  });
}

๐Ÿ”’ Security Best Practices

  1. API Key Management: Never expose your API key in client-side code for production
  2. Rate Limiting: Implement client-side rate limiting to avoid quota exhaustion
  3. Input Validation: Validate user input before geocoding
  4. Error Handling: Implement proper error boundaries
// 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
};

๐ŸŽฏ Performance Optimization

Bundle Size Optimization

// 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';

Caching Strategies

// 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

Debouncing and Throttling

// 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
};

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/opencagedata/svelte-sdk.git
cd svelte-sdk
npm install
npm run dev

Running Examples

cd examples/sveltekit-app
npm install
npm run dev

๐Ÿ“„ License

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.

๐Ÿ†˜ Support

๐Ÿ™ Acknowledgments

  • OpenCage Geocoding API for providing excellent geocoding services
  • Svelte team for the amazing framework
  • SvelteKit team for the full-stack framework
  • All contributors and users of this SDK

Author: Rome Stone

Top categories

Loading Svelte Themes