This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

TypeScript SDK for Cercalia

Type-safe TypeScript/JavaScript SDK for Cercalia APIs with Node.js and browser support, plus reference docs and source code links.

    Cercalia SDK for TypeScript

    TypeScript SDK

    A modern, type-safe TypeScript SDK for Cercalia web services. Build powerful location-based applications with geocoding, routing, POI search, and more—all with full TypeScript support for both Node.js and browser environments.

    Reference: https://docs.cercalia.com/docs/sdks/reference/typescript/

    Source code: https://github.com/Cercalia/cercalia-sdk-ts

    import { GeocodingService, RoutingService } from 'cercalia-sdk-ts';
    
    const geocoding = new GeocodingService({ apiKey: 'your-api-key' });
    const candidates = await geocoding.geocode({ 
      street: 'Gran Vía', 
      locality: 'Madrid' 
    });
    

    Table of Contents

    About Cercalia

    Cercalia is a comprehensive geospatial platform that provides mapping, geocoding, routing, and location intelligence services. Originally developed in Spain, Cercalia offers exceptional coverage of European markets with high-quality cartographic data and advanced spatial analysis capabilities.

    This SDK provides a clean, modern interface to Cercalia’s web services, abstracting away the complexity of raw API calls while preserving the full power of the platform.

    Features

    • 🎯 Type-Safe: Built with TypeScript strict mode—zero any types, full IntelliSense support
    • 🌐 Universal: Works seamlessly in Node.js (ESM/CommonJS) and browsers (via bundler)
    • 📦 Modern Architecture: Clean, modular design with tree-shakeable exports
    • 🔄 Comprehensive Services: 12+ geospatial services including:
      • Geocoding - Convert addresses to coordinates
      • Reverse Geocoding - Get addresses from coordinates
      • Routing - Calculate optimal routes with turn-by-turn directions
      • Suggest - Autocomplete and place suggestions
      • POI Search - Find points of interest
      • Isochrones - Calculate reachability areas
      • Proximity - Distance calculations and nearest neighbor search
      • Geofencing - Spatial boundary operations
      • Static Maps - Generate map images
      • And more…
    • 🛡️ Resilient: Built-in retry logic and error handling
    • 📝 Well-Documented: Inline JSDoc comments and comprehensive examples
    • 🧪 Tested: Full test coverage with Vitest

    Installation

    npm install cercalia-sdk-ts
    
    yarn add cercalia-sdk-ts
    
    pnpm add cercalia-sdk-ts
    

    Getting Your API Key

    Before using the SDK, you’ll need a Cercalia API key:

    1. Register for a Cercalia account at https://clients.cercalia.com/register
    2. Obtain your API key from your account dashboard
    3. Configure the SDK with your credentials (see Quick Start below)

    The API key authenticates your requests and tracks usage against your plan’s quota.

    Quick Start

    Here’s a simple example to get you started:

    import { setConfig, GeocodingService, RoutingService } from 'cercalia-sdk-ts';
    
    // Configure the SDK globally
    setConfig({
      cercalia: {
        apiKey: 'your-api-key-here',
        baseUrl: 'https://lb.cercalia.com/services/v2/json'
      },
      debug: false
    });
    
    // Geocode an address
    const geocoding = new GeocodingService();
    const results = await geocoding.geocode({
      street: 'Paseo de la Castellana, 1',
      locality: 'Madrid',
      countryCode: 'ESP'
    });
    
    console.log(results[0]);
    // {
    //   name: 'Paseo de la Castellana, 1, Madrid',
    //   coord: { lat: 40.419838, lng: -3.692580 },
    //   type: 'road',
    //   city: 'Madrid',
    //   region: 'Comunidad de Madrid',
    //   ...
    // }
    
    // Calculate a route
    const routing = new RoutingService();
    const route = await routing.calculateRoute(
      { lat: 40.419838, lng: -3.692580 },  // Origin
      { lat: 41.387015, lng: 2.170047 }    // Destination (Barcelona)
    );
    
    console.log(`Distance: ${(route.distance / 1000).toFixed(2)} km`);
    console.log(`Duration: ${(route.duration / 60).toFixed(0)} minutes`);
    

    Usage

    The SDK works identically in both Node.js and browser environments, but setup differs slightly.

    Backend (Node.js)

    Option 1: Environment Variables (Recommended)

    # .env file
    CERCALIA_API_KEY=your-api-key-here
    CERCALIA_BASE_URL=https://lb.cercalia.com/services/v2/json
    
    // The SDK automatically reads from process.env
    import { GeocodingService } from 'cercalia-sdk-ts';
    
    const geocoding = new GeocodingService();
    const results = await geocoding.geocode({ street: 'Gran Vía', locality: 'Madrid' });
    

    Option 2: Manual Configuration

    import { setConfig, GeocodingService } from 'cercalia-sdk-ts';
    
    setConfig({
      cercalia: {
        apiKey: 'your-api-key-here',
        baseUrl: 'https://lb.cercalia.com/services/v2/json'
      }
    });
    
    const geocoding = new GeocodingService();
    

    Option 3: Per-Service Configuration

    import { GeocodingService } from 'cercalia-sdk-ts';
    
    const geocoding = new GeocodingService({
      apiKey: 'your-api-key-here',
      baseUrl: 'https://lb.cercalia.com/services/v2/json'
    });
    

    Browser

    In browser environments, you must configure the SDK manually (no process.env access):

    <!DOCTYPE html>
    <html>
    <head>
      <title>Cercalia SDK Example</title>
    </head>
    <body>
      <script type="module">
        import { setConfig, GeocodingService } from 'https://unpkg.com/cercalia-sdk-ts';
    
        // Configure the SDK
        setConfig({
          cercalia: {
            apiKey: 'your-api-key-here'
          }
        });
    
        // Use services
        const geocoding = new GeocodingService();
        const results = await geocoding.geocode({ 
          street: 'Calle Alcalá', 
          locality: 'Madrid' 
        });
        
        console.log(results);
      </script>
    </body>
    </html>
    

    Using with Bundlers (Vite, Webpack, etc.)

    import { setConfig, GeocodingService } from 'cercalia-sdk-ts';
    
    setConfig({
      cercalia: {
        apiKey: import.meta.env.VITE_CERCALIA_API_KEY  // Vite
        // or: process.env.REACT_APP_CERCALIA_API_KEY  // Create React App
        // or: process.env.NEXT_PUBLIC_CERCALIA_API_KEY  // Next.js
      }
    });
    
    const geocoding = new GeocodingService();
    

    Security Note: Never expose your API key in client-side code for production applications. Consider using a backend proxy to authenticate requests.

    Core Services

    Geocoding

    Convert addresses and place names into geographic coordinates.

    import { GeocodingService } from 'cercalia-sdk-ts';
    
    const geocoding = new GeocodingService();
    
    // Basic address geocoding
    const results = await geocoding.geocode({
      street: 'Calle Alcalá, 42',
      locality: 'Madrid',
      countryCode: 'ESP'
    });
    
    console.log(results[0]);
    // {
    //   name: 'Calle Alcalá, 42, Madrid',
    //   coord: { lat: 40.419123, lng: -3.697421 },
    //   type: 'road',
    //   city: 'Madrid',
    //   cityId: '28079',
    //   region: 'Comunidad de Madrid',
    //   regionId: '28',
    //   country: 'España',
    //   countryId: 'ESP',
    //   postalCode: '28014',
    //   geometryType: 'rd'
    // }
    
    // Geocode with quality filter
    const preciseResults = await geocoding.geocode({
      street: 'Gran Vía, 1',
      locality: 'Madrid'
    }, {
      quality: 'street'  // Only return street-level matches
    });
    
    // Get multiple candidates
    const candidates = await geocoding.geocode({
      locality: 'Valencia'  // Multiple cities named Valencia
    }, {
      maxResults: 5
    });
    

    Key Features:

    • Address normalization and standardization
    • Multiple result candidates with quality scoring
    • Support for partial addresses
    • Administrative boundary information (city, region, country)
    • Geometry type metadata

    Reverse Geocoding

    Get address information from geographic coordinates.

    import { ReverseGeocodingService } from 'cercalia-sdk-ts';
    
    const reverseGeocoding = new ReverseGeocodingService();
    
    // Get address from coordinates
    const address = await reverseGeocoding.reverseGeocode({
      lat: 41.387015,
      lng: 2.170047
    });
    
    console.log(address);
    // {
    //   name: 'Plaça Catalunya, Barcelona',
    //   coord: { lat: 41.387015, lng: 2.170047 },
    //   type: 'road',
    //   city: 'Barcelona',
    //   region: 'Cataluña',
    //   postalCode: '08002',
    //   ...
    // }
    
    // Reverse geocode with radius
    const nearbyAddress = await reverseGeocoding.reverseGeocode(
      { lat: 40.416775, lng: -3.703790 },
      { radius: 100 }  // Search within 100 meters
    );
    

    Key Features:

    • Precise address resolution from coordinates
    • Configurable search radius
    • Nearest road/building detection
    • Full administrative hierarchy

    Routing

    Calculate optimal routes between locations with turn-by-turn directions.

    import { RoutingService } from 'cercalia-sdk-ts';
    
    const routing = new RoutingService();
    
    // Simple point-to-point route
    const route = await routing.calculateRoute(
      { lat: 40.416775, lng: -3.703790 },  // Madrid
      { lat: 41.387015, lng: 2.170047 }    // Barcelona
    );
    
    console.log(route);
    // {
    //   distance: 621458,  // meters
    //   duration: 21637,   // seconds
    //   wkt: 'LINESTRING(-3.703790 40.416775, ...)',
    //   geometry: [...],   // GeoJSON coordinates
    //   instructions: [
    //     {
    //       distance: 245,
    //       duration: 32,
    //       instruction: 'Head northeast on Calle Gran Vía',
    //       road: 'Gran Vía'
    //     },
    //     // ... more instructions
    //   ]
    // }
    
    // Route with waypoints
    const multiStopRoute = await routing.calculateRoute(
      { lat: 40.416775, lng: -3.703790 },
      { lat: 41.387015, lng: 2.170047 },
      {
        waypoints: [
          { lat: 41.648823, lng: -0.887618 }  // Zaragoza
        ]
      }
    );
    
    // Route with preferences
    const fastestRoute = await routing.calculateRoute(
      { lat: 40.416775, lng: -3.703790 },
      { lat: 41.387015, lng: 2.170047 },
      {
        vehicleType: 'car',
        routeType: 'fastest',  // or 'shortest', 'balanced'
        avoidTolls: true,
        avoidHighways: false
      }
    );
    
    // Get alternative routes
    const alternatives = await routing.calculateRoute(
      { lat: 40.416775, lng: -3.703790 },
      { lat: 41.387015, lng: 2.170047 },
      {
        alternatives: 3  // Get up to 3 alternative routes
      }
    );
    

    Key Features:

    • Turn-by-turn navigation instructions
    • Multiple route optimization strategies (fastest, shortest, balanced)
    • Support for waypoints and multi-stop routes
    • Vehicle-specific routing (car, truck, bicycle, pedestrian)
    • Route alternatives
    • Avoid tolls, highways, ferries
    • WKT and GeoJSON geometry output

    Other Available Services

    The SDK provides many more specialized services:

    • SuggestService - Autocomplete and place search suggestions

      const suggest = new SuggestService();
      const suggestions = await suggest.suggest({ text: 'Restaurante en Madrid' });
      
    • POIService - Search for points of interest

      const poi = new POIService();
      const restaurants = await poi.search({ category: 'restaurant', location: { lat: 40.416, lng: -3.703 } });
      
    • IsochroneService - Calculate reachability areas (how far can you travel in X minutes?)

      const isochrone = new IsochroneService();
      const area = await isochrone.calculate({ lat: 40.416, lng: -3.703 }, { time: 30 });
      
    • ProximityService - Distance calculations and nearest neighbor search

      const proximity = new ProximityService();
      const nearest = await proximity.findNearest({ lat: 40.416, lng: -3.703 }, targets);
      
    • GeofencingService - Point-in-polygon and spatial boundary operations

      const geofencing = new GeofencingService();
      const isInside = await geofencing.contains(point, polygon);
      
    • SnapToRoadService - Snap GPS coordinates to road network

      const snapToRoad = new SnapToRoadService();
      const snapped = await snapToRoad.snap(gpsPoints);
      
    • StaticMapsService - Generate static map images

      const staticMaps = new StaticMapsService();
      const imageUrl = await staticMaps.getMap({ center: { lat: 40.416, lng: -3.703 }, zoom: 14 });
      
    • GeomentService - Advanced geocoding with entity recognition

      const geoment = new GeomentService();
      const entities = await geoment.geocode('Calle Alcalá 42, Madrid');
      

    See the examples directory for complete, runnable code samples for each service.

    Advanced Configuration

    Debug Logging

    Enable detailed logging to troubleshoot API calls:

    import { setConfig } from 'cercalia-sdk-ts';
    
    setConfig({
      cercalia: {
        apiKey: 'your-api-key'
      },
      debug: true  // Enable debug logging
    });
    
    // Logs will show:
    // - Request URLs and parameters
    // - Response status and timing
    // - Error details
    

    Custom Base URL

    If you’re using a Cercalia private instance or proxy:

    setConfig({
      cercalia: {
        apiKey: 'your-api-key',
        baseUrl: 'https://your-custom-domain.com/cercalia/v2/json'
      }
    });
    

    Retry Configuration

    The SDK includes built-in retry logic for transient failures. Customize it per service:

    import { GeocodingService } from 'cercalia-sdk-ts';
    
    const geocoding = new GeocodingService({
      apiKey: 'your-api-key',
      maxRetries: 3,      // Number of retry attempts
      retryDelay: 1000    // Delay between retries (ms)
    });
    

    Error Handling

    All services throw typed errors that you can catch and handle:

    import { GeocodingService } from 'cercalia-sdk-ts';
    
    const geocoding = new GeocodingService();
    
    try {
      const results = await geocoding.geocode({ street: 'Invalid Address' });
    } catch (error) {
      if (error instanceof Error) {
        console.error('Geocoding failed:', error.message);
        
        // Check for specific error types
        if (error.message.includes('API key')) {
          console.error('Invalid API key');
        } else if (error.message.includes('quota')) {
          console.error('API quota exceeded');
        }
      }
    }
    

    Examples

    The SDK includes comprehensive examples for both TypeScript and browser environments:

    TypeScript Examples

    Located in examples/typescript/src/:

    Run the examples:

    cd examples/typescript
    npm install
    npm run dev
    

    Browser Examples

    Located in examples/browser/:

    Interactive HTML pages demonstrating each service with live UI. Open index.html in your browser to explore all examples.

    Each example includes:

    • Form-based input
    • Real-time API calls
    • Result visualization
    • Map integration (where applicable)

    Documentation

    Official Cercalia Documentation

    For detailed API reference, advanced features, and service-specific parameters, visit the official Cercalia documentation:

    https://docs.cercalia.com/docs/

    The official docs cover:

    • Complete API reference for all services
    • Advanced parameters and options
    • Response format specifications
    • Rate limits and quotas
    • Best practices and optimization tips
    • Regional coverage details

    SDK Documentation

    • Type Definitions: The SDK is fully typed. Use your IDE’s IntelliSense (Ctrl+Space) to explore available methods and parameters.
    • Source Code: All services include inline JSDoc comments. Read the source in src/services/ for implementation details.
    • Tests: The test suite in tests/ provides additional usage examples and edge cases.

    Getting Help

    1. Check the examples - Most common use cases are covered
    2. Read the official docs - https://docs.cercalia.com/docs/
    3. Review TypeScript types - IntelliSense will show you all available options
    4. Open an issue - For SDK-specific bugs or feature requests

    License

    This SDK is provided for use with Cercalia web services. Please refer to your Cercalia service agreement for terms of use.

    For questions about licensing, contact Cercalia.


    Built with TypeScript | Powered by Cercalia | Documentation | Get API Key