Official Angular SDK for OpenCage Geocoding API - Professional-grade geocoding services with TypeScript support, RxJS integration, and comprehensive error handling
npm install @digiphilo/opencage-angular


> π Official Angular SDK for the OpenCage Geocoding API
A comprehensive, production-ready Angular library that provides seamless integration with the OpenCage Geocoding API. Built with TypeScript, RxJS, and modern Angular patterns.
- π Modern Angular: Built for Angular 15+ with standalone component support
- π Reactive: Full RxJS integration with Observables and operators
- π‘οΈ Type Safe: Complete TypeScript definitions and interfaces
- π― Smart Caching: Configurable in-memory caching with TTL and LRU eviction
- β‘ Rate Limiting: Built-in rate limiting with backoff strategies
- π§ Configurable: Extensive configuration options for all use cases
- π¨ UI Components: Ready-to-use pipes and directives
- β
Validated: Form validation directives for coordinates
- π§ͺ Well Tested: Comprehensive unit tests with high coverage
- π¦ Tree Shakable: Optimized for minimal bundle size
- π Universal: Supports both browser and server-side rendering
``bash`
npm install @opencagedata/angular-sdk
`typescript
import { NgModule } from '@angular/core';
import { OpenCageAngularModule } from '@opencagedata/angular-sdk';
@NgModule({
imports: [
OpenCageAngularModule.forRoot({
apiKey: 'YOUR_OPENCAGE_API_KEY',
enableCaching: true,
enableRateLimit: true
})
],
// ...
})
export class AppModule { }
`
`typescript
import { bootstrapApplication } from '@angular/platform-browser';
import { provideOpenCage } from '@opencagedata/angular-sdk';
bootstrapApplication(AppComponent, {
providers: [
provideOpenCage({
apiKey: 'YOUR_OPENCAGE_API_KEY',
enableCaching: true,
enableRateLimit: true
})
]
});
`
`typescript
import { Component } from '@angular/core';
import { OpenCageService } from '@opencagedata/angular-sdk';
@Component({
selector: 'app-geocoding',
template:
{{ result.geometry | coordinateFormat:'dms' }}
Confidence: {{ result.confidence | confidence:'stars' }}
})
export class GeocodingComponent {
query = '';
results: any[] = []; constructor(private geocode: OpenCageService) {}
geocode() {
this.geocode.geocode(this.query).subscribe(response => {
this.results = response.results;
});
}
}
`π― Core Services
$3
The main service for geocoding operations:
`typescript
import { OpenCageService } from '@opencagedata/angular-sdk';// Forward geocoding
geocodeService.geocode('Berlin, Germany')
.subscribe(response => console.log(response.results));
// Reverse geocoding
geocodeService.reverseGeocode({ lat: 52.517, lng: 13.389 })
.subscribe(response => console.log(response.results));
// Get first result only
geocodeService.geocodeFirst('London')
.subscribe(result => console.log(result?.formatted));
// Batch processing
const requests = [
{ query: 'Berlin' },
{ query: 'London' },
{ query: 'New York' }
];
geocodeService.batchGeocode(requests)
.subscribe(response => console.log(response.responses));
// Stream processing
geocodeService.streamGeocode(['Berlin', 'London', 'Paris'])
.subscribe(result => console.log(result));
`$3
`typescript
// Use promises instead of observables
const response = await geocodeService.geocodePromise('Berlin');
const result = await geocodeService.reverseGeocodePromise({ lat: 52.517, lng: 13.389 });
`π¨ UI Components
$3
#### Coordinate Formatting
`html
{{ coordinates | coordinateFormat:'decimal':6 }}
{{ coordinates | coordinateFormat:'dms' }}
{{ coordinates | coordinateCustom:'Lat: {lat}Β°, Lng: {lng}Β°':4 }}
`#### Address Formatting
`html
{{ result | addressFormat:'long' }}
{{ result | addressFormat:'short' }}
{{ result | addressFormat:'postal' }}
{{ result | addressComponents:['road', 'city', 'country']:' β ' }}
{{ result | addressComponent:'country' }}
{{ result.confidence | confidence:'stars' }}
{{ result.confidence | confidence:'percentage' }}
`$3
#### Geocoding Input with Auto-complete
`html
type="text"
opencageGeocode
[debounceTime]="500"
[minLength]="3"
[limit]="5"
(geocodeResults)="onResults($event)"
(geocodeSelected)="onSelected($event)"
placeholder="Start typing..."
/>
`#### Coordinate Validation
`html
type="number"
coordinateValidator="latitude"
[(ngModel)]="latitude"
/>
type="number"
coordinateValidator="longitude"
[(ngModel)]="longitude"
/>
type="text"
coordinateValidator="both"
[(ngModel)]="coordinates"
placeholder="52.517, 13.389"
/>
`#### Reactive Forms Validators
`typescript
import { CoordinateValidators } from '@opencagedata/angular-sdk';this.form = this.fb.group({
latitude: ['', [Validators.required, CoordinateValidators.latitude]],
longitude: ['', [Validators.required, CoordinateValidators.longitude]],
coordinates: ['', CoordinateValidators.coordinates],
customRange: ['', CoordinateValidators.range(40, 60, 0, 20)],
precision: ['', CoordinateValidators.precision(4)]
});
`βοΈ Configuration
$3
`typescript
interface OpenCageConfig {
apiKey: string; // Required: Your OpenCage API key
baseUrl?: string; // API base URL (default: official API)
defaultLanguage?: string; // Default language for results
enableCaching?: boolean; // Enable response caching
cacheTtl?: number; // Cache TTL in milliseconds
enableRateLimit?: boolean; // Enable rate limiting
rateLimit?: number; // Requests per second limit
timeout?: number; // Request timeout in milliseconds
retryAttempts?: number; // Number of retry attempts
retryDelay?: number; // Delay between retries
debug?: boolean; // Enable debug logging
}
`$3
`typescript
// Development
OpenCageConfigService.forEnvironment('development')// Production
OpenCageConfigService.forEnvironment('production')
// Testing
OpenCageConfigService.forEnvironment('test')
`$3
`typescript
constructor(private configService: OpenCageConfigService) {}updateConfig() {
this.configService.updateConfig({
enableCaching: false,
timeout: 5000
});
}
`π Advanced Features
$3
`typescript
import { OpenCageCacheService } from '@opencagedata/angular-sdk';// Get cache statistics
const stats = cacheService.getStats();
console.log(
Cache size: ${stats.size}, Hit rate: ${stats.hitRate});// Manual cache management
cacheService.clear();
cacheService.cleanup(); // Remove expired entries
cacheService.setMaxSize(500);
`$3
`typescript
import { OpenCageRateLimiterService } from '@opencagedata/angular-sdk';// Configure rate limiter
rateLimiter.configure({
rps: 5, // 5 requests per second
backoffStrategy: 'exponential',
maxDelay: 30000
});
// Get statistics
const stats = rateLimiter.getStats();
console.log(
Available tokens: ${stats.availableTokens});
`$3
`typescript
import { OpenCageError, isOpenCageError } from '@opencagedata/angular-sdk';geocodeService.geocode('invalid query').subscribe({
next: response => console.log(response),
error: (error: OpenCageError) => {
console.log(
Error type: ${error.type});
console.log(Retryable: ${error.isRetryable()});
console.log(User message: ${OpenCageErrorHandler.getUserFriendlyMessage(error)});
if (error.isRetryable()) {
const delay = error.getRetryDelay();
console.log(Retry in ${delay}ms);
}
}
});
`π± Complete Examples
$3
`typescript
@Component({
selector: 'app-address-input',
standalone: true,
imports: [CommonModule, FormsModule, OPENCAGE_IMPORTS],
template:
{{ selected.formatted }}
Coordinates: {{ selected.geometry | coordinateFormat:'dms' }}
Components: {{ selected | addressComponents:['house_number', 'road', 'city', 'state_code', 'postcode'] }}
Country: {{ selected | addressComponent:'country' }} ({{ selected | isCountry:'us' ? 'πΊπΈ' : 'π' }})
,
styles: []
})
export class AddressInputComponent {
results: GeocodingResult[] = [];
loading = false;
selected: GeocodingResult | null = null; selectResult(result: GeocodingResult, input: HTMLInputElement) {
input.value = result.formatted;
this.selected = result;
this.results = [];
}
onSelected(result: GeocodingResult) {
this.selected = result;
}
}
`$3
`typescript
@Component({
selector: 'app-batch-geocoder',
template:
})
export class BatchGeocoderComponent {
addressList = 'Berlin, Germany\nLondon, UK\nParis, France\nNew York, USA';
processing = false;
progress = 0;
processed = 0;
total = 0;
results: Array<{query: string, result?: GeocodingResult}> = []; constructor(private geocodeService: OpenCageService) {}
processBatch() {
const addresses = this.addressList.split('\n')
.map(addr => addr.trim())
.filter(addr => addr.length > 0);
if (addresses.length === 0) return;
this.processing = true;
this.results = [];
this.processed = 0;
this.total = addresses.length;
this.progress = 0;
// Process with streaming for progress updates
this.geocodeService.streamGeocode(addresses)
.subscribe({
next: ({ query, response, index }) => {
this.processed++;
this.progress = (this.processed / this.total) * 100;
this.results.push({
query,
result: response.results[0] || undefined
});
// Sort results by original order
this.results.sort((a, b) =>
addresses.indexOf(a.query) - addresses.indexOf(b.query)
);
},
error: error => {
console.error('Batch processing error:', error);
this.processing = false;
},
complete: () => {
this.processing = false;
console.log(
Batch processing complete: ${this.results.length} results);
}
});
}
}
`π§ͺ Testing
$3
`bash
Run unit tests
npm testRun tests with coverage
npm run test:coverageRun tests in watch mode
npm run test:watch
`$3
`typescript
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { OpenCageAngularModule } from '@opencagedata/angular-sdk';describe('MyComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
OpenCageAngularModule.forRoot({
apiKey: 'test-key'
})
]
});
});
});
`ποΈ Building
`bash
Build the library
npm run buildBuild for production
npm run build:prodPack for distribution
npm run pack
`π Migration Guide
$3
`typescript
// Before (Google Maps)
geocoder.geocode({ address: query }, (results, status) => {
if (status === 'OK') {
console.log(results[0].formatted_address);
}
});// After (OpenCage)
geocodeService.geocode(query).subscribe(response => {
console.log(response.results[0].formatted);
});
`$3
The OpenCage SDK provides a more consistent, type-safe, and feature-rich experience:
- Type Safety: Full TypeScript support
- Reactive: RxJS observables instead of callbacks
- Error Handling: Comprehensive error types and handling
- Caching: Built-in intelligent caching
- Rate Limiting: Automatic rate limit management
- UI Components: Ready-to-use pipes and directives
π Performance Tips
1. Enable Caching: Reduces redundant API calls
2. Use Rate Limiting: Prevents hitting API limits
3. Batch Processing: Process multiple addresses efficiently
4. Tree Shaking: Import only what you need
5. Lazy Loading: Load geocoding features only when needed
`typescript
// Tree-shaking friendly imports
import { OpenCageService } from '@opencagedata/angular-sdk/service';
import { CoordinateFormatPipe } from '@opencagedata/angular-sdk/pipes';
`π€ Contributing
We welcome contributions! Please see our Contributing Guide for details.
1. Fork the repository
2. Create your feature branch (
git checkout -b feature/amazing-feature)
3. Commit your changes (git commit -m 'Add amazing feature')
4. Push to the branch (git push origin feature/amazing-feature`)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.
- π§ Email: support@opencagedata.com
- π Issues: GitHub Issues
- π Documentation: OpenCage API Docs
- π¬ Community: OpenCage Community
- Powered by the OpenCage Geocoding API
- Thanks to all contributors
---
Author: Rome Stone