npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@digiphilo/opencage-angular-development

v1.3.0

Published

[![npm version](https://badge.fury.io/js/%40opencagedata%2Fangular-sdk.svg)](https://badge.fury.io/js/%40opencagedata%2Fangular-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Build Statu

Downloads

165

Readme

OpenCage Angular SDK

npm version License: MIT Build Status

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

✨ Features

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

📦 Installation

npm install @opencagedata/angular-sdk

🚀 Quick Start

1. Module Setup (Traditional Angular)

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

2. Standalone Setup (Angular 14+)

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

3. Basic Usage

import { Component } from '@angular/core';
import { OpenCageService } from '@opencagedata/angular-sdk';

@Component({
  selector: 'app-geocoding',
  template: `
    <input [(ngModel)]="query" placeholder="Enter address">
    <button (click)="geocode()">Search</button>
    
    <div *ngFor="let result of results">
      <h3>{{ result.formatted }}</h3>
      <p>{{ result.geometry | coordinateFormat:'dms' }}</p>
      <p>Confidence: {{ result.confidence | confidence:'stars' }}</p>
    </div>
  `
})
export class GeocodingComponent {
  query = '';
  results: any[] = [];

  constructor(private geocode: OpenCageService) {}

  geocode() {
    this.geocode.geocode(this.query).subscribe(response => {
      this.results = response.results;
    });
  }
}

🎯 Core Services

OpenCageService

The main service for geocoding operations:

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

Promise Support

// Use promises instead of observables
const response = await geocodeService.geocodePromise('Berlin');
const result = await geocodeService.reverseGeocodePromise({ lat: 52.517, lng: 13.389 });

🎨 UI Components

Pipes

Coordinate Formatting

<!-- Decimal degrees -->
{{ coordinates | coordinateFormat:'decimal':6 }}
<!-- Output: 52.517037, 13.388860 -->

<!-- Degrees, Minutes, Seconds -->
{{ coordinates | coordinateFormat:'dms' }}
<!-- Output: 52°31'1.33"N, 13°23'19.90"E -->

<!-- Custom format -->
{{ coordinates | coordinateCustom:'Lat: {lat}°, Lng: {lng}°':4 }}
<!-- Output: Lat: 52.5170°, Lng: 13.3889° -->

Address Formatting

<!-- Full address -->
{{ result | addressFormat:'long' }}

<!-- Short address -->
{{ result | addressFormat:'short' }}

<!-- Postal format -->
{{ result | addressFormat:'postal' }}

<!-- Custom components -->
{{ result | addressComponents:['road', 'city', 'country']:' → ' }}

<!-- Individual component -->
{{ result | addressComponent:'country' }}

<!-- Confidence display -->
{{ result.confidence | confidence:'stars' }}
{{ result.confidence | confidence:'percentage' }}

Directives

Geocoding Input with Auto-complete

<input 
  type="text"
  opencageGeocode
  [debounceTime]="500"
  [minLength]="3"
  [limit]="5"
  (geocodeResults)="onResults($event)"
  (geocodeSelected)="onSelected($event)"
  placeholder="Start typing..."
/>

Coordinate Validation

<!-- Validate latitude -->
<input 
  type="number"
  coordinateValidator="latitude"
  [(ngModel)]="latitude"
/>

<!-- Validate longitude -->
<input 
  type="number"
  coordinateValidator="longitude"
  [(ngModel)]="longitude"
/>

<!-- Validate coordinate pair -->
<input 
  type="text"
  coordinateValidator="both"
  [(ngModel)]="coordinates"
  placeholder="52.517, 13.389"
/>

Reactive Forms Validators

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

Configuration Options

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
}

Environment-specific Configuration

// Development
OpenCageConfigService.forEnvironment('development')

// Production
OpenCageConfigService.forEnvironment('production')

// Testing
OpenCageConfigService.forEnvironment('test')

Dynamic Configuration Updates

constructor(private configService: OpenCageConfigService) {}

updateConfig() {
  this.configService.updateConfig({
    enableCaching: false,
    timeout: 5000
  });
}

🔄 Advanced Features

Caching

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

Rate Limiting

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

Error Handling

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

Geocoding with Auto-complete Component

@Component({
  selector: 'app-address-input',
  standalone: true,
  imports: [CommonModule, FormsModule, OPENCAGE_IMPORTS],
  template: `
    <div class="autocomplete-container">
      <input 
        #input
        type="text"
        opencageGeocode
        [debounceTime]="300"
        [minLength]="2"
        [limit]="8"
        [options]="{ countrycode: 'us' }"
        (geocodeResults)="results = $event"
        (geocodeLoading)="loading = $event"
        (geocodeSelected)="onSelected($event)"
        placeholder="Enter US address..."
        [class.loading]="loading"
      />
      
      <div class="dropdown" *ngIf="results.length > 0">
        <div 
          *ngFor="let result of results"
          (click)="selectResult(result, input)"
          class="dropdown-item"
        >
          <div class="address">{{ result.formatted }}</div>
          <div class="coords">{{ result.geometry | coordinateFormat:'decimal':4 }}</div>
          <div class="confidence">{{ result.confidence | confidence:'stars' }}</div>
        </div>
      </div>
    </div>

    <div *ngIf="selected" class="selected-address">
      <h3>Selected Address:</h3>
      <p><strong>{{ selected.formatted }}</strong></p>
      <p>Coordinates: {{ selected.geometry | coordinateFormat:'dms' }}</p>
      <p>Components: {{ selected | addressComponents:['house_number', 'road', 'city', 'state_code', 'postcode'] }}</p>
      <p>Country: {{ selected | addressComponent:'country' }} ({{ selected | isCountry:'us' ? '🇺🇸' : '🌍' }})</p>
    </div>
  `,
  styles: [`
    .autocomplete-container { position: relative; }
    .dropdown {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      background: white;
      border: 1px solid #ddd;
      max-height: 300px;
      overflow-y: auto;
      z-index: 1000;
    }
    .dropdown-item {
      padding: 12px;
      cursor: pointer;
      border-bottom: 1px solid #eee;
    }
    .dropdown-item:hover { background: #f5f5f5; }
    .loading { opacity: 0.7; }
    .selected-address {
      margin-top: 20px;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 8px;
    }
  `]
})
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;
  }
}

Batch Geocoding with Progress

@Component({
  selector: 'app-batch-geocoder',
  template: `
    <div class="batch-geocoder">
      <h2>Batch Geocoding</h2>
      
      <textarea 
        [(ngModel)]="addressList"
        placeholder="Enter addresses, one per line..."
        rows="6"
      ></textarea>
      
      <button 
        (click)="processBatch()" 
        [disabled]="processing"
        class="process-btn"
      >
        {{ processing ? 'Processing...' : 'Geocode All' }}
      </button>

      <div *ngIf="processing" class="progress">
        <div class="progress-bar" [style.width.%]="progress"></div>
        <span>{{ processed }}/{{ total }} processed</span>
      </div>

      <div *ngIf="results.length > 0" class="results">
        <h3>Results ({{ results.length }} addresses)</h3>
        <div *ngFor="let item of results; let i = index" class="result-item">
          <div class="query">{{ item.query }}</div>
          <div *ngIf="item.result" class="success">
            ✅ {{ item.result.formatted }}
            <span class="coords">({{ item.result.geometry | coordinateFormat:'decimal':4 }})</span>
          </div>
          <div *ngIf="!item.result" class="error">❌ No results found</div>
        </div>
      </div>
    </div>
  `
})
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

Running Tests

# Run unit tests
npm test

# Run tests with coverage
npm run test:coverage

# Run tests in watch mode
npm run test:watch

Testing with the SDK

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

# Build the library
npm run build

# Build for production
npm run build:prod

# Pack for distribution
npm run pack

🌟 Migration Guide

From Google Maps Geocoding

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

From Other Libraries

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
// 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)
  5. Open a Pull Request

📄 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


Author: Rome Stone