Geocoding

The Geocoding service converts addresses and place names into precise geographic coordinates, providing detailed location information including formatted addresses, place categories, and geographic boundaries. This service is essential for location-based applications that need to transform human-readable addresses into mappable coordinates.

import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
import { geocode } from '@tomtom-org/maps-sdk/services';
import { API_KEY } from './config';

TomTomConfig.instance.put({ apiKey: API_KEY });

(async () => {
    const result = await geocode({ query: 'Rue Pepin', limit: 3 });
    console.log(JSON.stringify(result, null, 4));
})();

Core Geocoding Concepts

Geocoding serves as the bridge between human-readable location descriptions and machine-processable geographic coordinates. The service handles various input formats, from complete street addresses to partial location descriptions, and returns structured geographic data suitable for mapping and analysis.

Primary Use Cases:

  • Address validation and standardization for data quality
  • Location search in booking and reservation systems
  • Coordinate lookup for mapping and navigation applications
  • Bulk address processing for logistics and delivery optimization

Basic Geocoding Usage

Simplest Single Address Geocoding

For the quickest way to geocode a single address when you only need the top result, use geocodeOne:

import { geocodeOne } from '@tomtom-org/maps-sdk/services';
const place = await geocodeOne('Dam Square, Amsterdam, Netherlands');
const coordinates = place.geometry.coordinates; // [longitude, latitude]

This convenience function automatically returns just the most relevant result, making it ideal for simple address lookups where you don’t need multiple candidates or additional configuration.

Standard Address Geocoding

When you need more control over the geocoding results or want to retrieve multiple candidates, use the standard geocode function:

import { geocode } from '@tomtom-org/maps-sdk/services';
const result = await geocode({
query: 'Dam Square, Amsterdam, Netherlands'
});
const coordinates = result.features[0].geometry.coordinates; // [longitude, latitude]

This approach provides access to all geocoding parameters and returns the full result set, allowing you to handle multiple matches or apply advanced filtering.

Structured Address Input

For enhanced accuracy and reliability, especially in data processing scenarios, use structured address components:

const result = await geocode({
query: 'Dam Square',
countrySet: ['NL'],
locality: 'Amsterdam',
postalCode: '1012'
});

Benefits of Structured Input:

  • Higher accuracy through component-specific matching
  • Reduced ambiguity in location resolution
  • Better handling of incomplete or partial addresses
  • Improved performance through targeted searching

Advanced Geocoding Configuration

Geographic Constraints and Biasing

Control geocoding results by applying geographic constraints that bias results toward specific regions or limit search scope:

// Bias results toward Amsterdam area
const result = await geocode({
query: 'Central Station',
position: [4.9041, 52.3676], // Amsterdam center coordinates
countrySet: ['NL']
});
// Search within a specific bounding box
const result = await geocode({
query: 'Main Street',
boundingBox: [4.7, 52.2, 5.1, 52.5] // Amsterdam metropolitan area
});

Geographic Constraint Benefits:

  • Improved relevance for location-specific applications
  • Faster processing through reduced search scope
  • Better disambiguation for common place names
  • Regional accuracy for multi-national applications

Multiple Result Handling

When dealing with ambiguous location names or when you need alternative options, request multiple geocoding candidates:

const results = await geocode({
query: 'Paris', // Matches multiple cities worldwide
limit: 5
});
results.features.forEach(place => {
const address = place.properties.address;
console.log(`${address.municipality}, ${address.country}`);
console.log(place.geometry.coordinates); // [longitude, latitude]
});

This approach is particularly valuable for:

  • Location disambiguation in user interfaces
  • Alternative suggestions for unclear inputs
  • Comprehensive search results for travel and booking applications

Working with Geocoding Results

Result Data Structure

Geocoding results follow the GeoJSON specification and provide comprehensive location information:

const result = await geocode({
query: 'Amsterdam Central Station'
});
const place = result.features[0];
// Extract coordinate information
const [longitude, latitude] = place.geometry.coordinates;
// Access detailed address components
const address = place.properties.address;
console.log(address.freeformAddress); // Complete formatted address
console.log(address.municipality); // Amsterdam
console.log(address.country); // Netherlands
console.log(address.postalCode); // Postal code if available
// Retrieve place category information
console.log(place.properties.poi?.categories); // ['RAILWAY_STATION']

Address Component Hierarchy:

  • streetNumber: Specific building number
  • streetName: Street or road name
  • municipality: City or town name
  • postalCode: Postal or ZIP code
  • country: Country name
  • freeformAddress: Complete formatted address string

Integration with Mapping

Geocoding results integrate seamlessly with the TomTom Maps SDK for immediate visualization:

import { TomTomMap, PlacesModule } from '@tomtom-org/maps-sdk/map';
const map = new TomTomMap({ mapLibre: { container: 'map' } });
const placesModule = await PlacesModule.get(map);
const result = await geocode({
query: 'Amsterdam Museum District'
});
// Display geocoded location on map
placesModule.addPlaces({
id: 'geocoded-location',
places: result.features
});

Performance and Best Practices

Optimization Strategies

For production applications processing multiple addresses, implement these optimization techniques:

Caching Strategy:

  • Cache frequent address lookups to reduce API calls
  • Store results for commonly searched locations
  • Implement intelligent cache invalidation policies

Request Optimization:

  • Use structured queries when possible for better accuracy
  • Apply appropriate geographic constraints to improve performance
  • Batch similar requests when feasible

Error Handling:

try {
const result = await geocode({
query: 'Nonexistent Address 123'
});
if (result.features.length === 0) {
console.log('No results found for the given address');
// Handle no results scenario
}
} catch (error) {
console.error('Geocoding failed:', error.message);
// Implement fallback strategies
}

For comprehensive geocoding implementation examples and advanced usage patterns, go to http://docs.tomtom.com/maps-sdk-js/examples .

Map Integration

  • Places Module - Display geocoded locations as interactive places on the map with styling and popups
  • Routing Module - Use geocoded addresses as waypoints for route planning and navigation