Utilities
The Core bundle provides a collection of utility functions that help you work with geographic data, format values for display, and handle common operations across the Maps SDK.
Working with Coordinates
getPosition
Extracts lng-lat coordinates from various input formats into a standard GeoJSON Position array [longitude, latitude].
Supported input formats:
- Raw coordinate arrays:
[lng, lat] - GeoJSON Point geometries
- GeoJSON Point Features (including Places)
import { getPosition } from '@tomtom-org/maps-sdk/core';
// From coordinate arrayconst pos1 = getPosition([4.9, 52.3]);// Returns: [4.9, 52.3]
// From Point geometryconst pos2 = getPosition({ type: 'Point', coordinates: [4.9, 52.3]});// Returns: [4.9, 52.3]
// From a Place Featureconst place = await geocode({ key: 'your-api-key', query: 'Amsterdam' });const pos3 = getPosition(place);// Returns: [longitude, latitude]
// From a Place with entry point preferenceconst pos4 = getPosition(place, { useEntryPoint: 'main-when-available' });// Returns entry point coordinates if available, otherwise geometry coordinatesEntry point options:
When working with Places that have entry points (building entrances), you can specify which position to extract:
useEntryPoint: 'main-when-available'– Use the main entry point coordinates if available, otherwise fall back to the geometry coordinates
Returns: Position | null – The coordinates as [longitude, latitude], or null if input is invalid.
Working with Bounding Boxes
bboxFromGeoJSON
Calculates or extracts bounding boxes from GeoJSON objects. The function intelligently handles various GeoJSON types and optimizes performance:
- Uses existing
bboxproperties when available (fastest) - Calculates from geometry coordinates when needed
- Aggregates bounding boxes from collections
- Optimizes large geometries by sampling points
Key behavior: The function prioritizes existing bbox fields over geometry calculations, which is important for Point features from TomTom services that may have a bbox representing a broader area than just the point location.
import { bboxFromGeoJSON } from '@tomtom-org/maps-sdk/core';
// From a Place with existing bboxconst place = await geocode({ key: 'your-api-key', query: 'Amsterdam' });const bbox1 = bboxFromGeoJSON(place);// Returns the bbox that came with the place
// From a Polygon geometry (calculates bbox)const polygon = { type: 'Polygon', coordinates: [[ [4.88, 52.36], [4.90, 52.36], [4.90, 52.38], [4.88, 52.38], [4.88, 52.36] ]]};const bbox2 = bboxFromGeoJSON(polygon);// Returns: [4.88, 52.36, 4.90, 52.38]
// From a FeatureCollection (aggregates all features)const places = await search({ key: 'your-api-key', query: 'coffee' });const bbox3 = bboxFromGeoJSON(places);// Returns bbox encompassing all search results
// From a LineString (calculates from coordinates)const route = await calculateRoute({ key: 'your-api-key', locations: [[4.9, 52.3], [4.5, 51.9]]});const bbox4 = bboxFromGeoJSON(route.routes[0].geometry);// Returns bbox containing the entire route
// From an array of GeoJSON objectsconst bbox5 = bboxFromGeoJSON([place1, place2, place3]);// Returns bbox encompassing all three placesReturns: [minLng, minLat, maxLng, maxLat] | undefined – The bounding box, or undefined if input is invalid.
polygonFromBBox
Converts a bounding box into a GeoJSON Polygon Feature, useful for visualizing bounding box areas on a map.
import { polygonFromBBox } from '@tomtom-org/maps-sdk/core';
// Create a polygon from a bboxconst bbox = [4.88, 52.36, 4.90, 52.38];const polygon = polygonFromBBox(bbox);// Returns a GeoJSON Feature with Polygon geometry
// Visualize a bbox on a mapconst places = await search({ key: 'your-api-key', query: 'coffee' });const bbox = bboxFromGeoJSON(places);if (bbox) { const bboxPolygon = polygonFromBBox(bbox); map.addSource('bbox-area', { type: 'geojson', data: bboxPolygon }); map.addLayer({ id: 'bbox-outline', type: 'line', source: 'bbox-area', paint: { 'line-color': '#3887be', 'line-width': 2 } });}Parameters:
bbox– Bounding box as[west, south, east, north]
Returns: Feature<Polygon> – A GeoJSON Feature with a closed Polygon geometry representing the bbox area.
Formatting Values
formatDuration
Formats a duration in seconds into a human-readable time string with intelligent rounding based on duration length.
Rounding behavior:
- Durations under 30 seconds return
undefined - 30-59 seconds round to “1 min”
- Minutes are rounded to nearest minute
- Hours are displayed when duration ≥ 1 hour
import { formatDuration } from '@tomtom-org/maps-sdk/core';
formatDuration(0); // undefined (too short)formatDuration(20); // undefined (too short)formatDuration(30); // "1 min"formatDuration(60); // "1 min"formatDuration(100); // "2 min"formatDuration(1800); // "30 min"formatDuration(3599); // "1 hr 00 min"formatDuration(3660); // "1 hr 01 min"formatDuration(7200); // "2 hr 00 min"formatDuration(36120); // "10 hr 02 min"
// Custom unitsformatDuration(3660, { hours: 'h', minutes: 'm' });// Returns: "1 h 01 m"
// Route travel timeconst route = await calculateRoute({ /* ... */ });const travelTime = formatDuration(route.routes[0].summary.travelTimeInSeconds);console.log(`Estimated time: ${travelTime}`);// Output: "Estimated time: 2 hr 15 min"Parameters:
seconds– The duration in secondsoptions– Optional custom display units for hours and minutes
Returns: string | undefined – Formatted time string, or undefined if duration is too short.
formatDistance
Formats distance in meters into a human-readable string with appropriate units and precision based on the distance. Supports metric, US imperial, and UK imperial unit systems.
Unit systems:
-
metric(International System)- Units: meters (m), kilometers (km)
- Used in most of the world
- Decimal-based, no fractions
-
imperial_us(United States)- Units: feet (ft), miles (mi)
- Uses fractions for miles (¼, ½, ¾)
- Feet for short distances (< 0.125 mi)
-
imperial_uk(United Kingdom)- Units: yards (yd), miles (mi)
- Uses fractions for miles (¼, ½, ¾)
- Yards for short distances (< 0.125 mi)
import { formatDistance } from '@tomtom-org/maps-sdk/core';
// Metric formatting (default)formatDistance(0); // "0 m"formatDistance(2); // "2 m"formatDistance(237); // "240 m"formatDistance(730); // "700 m"formatDistance(950); // "1 km"formatDistance(-999); // "-1 km"formatDistance(2850); // "2.9 km"formatDistance(283520); // "284 km"
// US Imperial formattingformatDistance(2, { type: 'imperial_us' });// Returns: "7 ft"
formatDistance(100, { type: 'imperial_us' });// Returns: "330 ft"
formatDistance(205.95, { type: 'imperial_us' });// Returns: "¼ mi"
formatDistance(1205.95, { type: 'imperial_us' });// Returns: "¾ mi"
formatDistance(5309.7, { type: 'imperial_us' });// Returns: "3½ mi"
formatDistance(-18181.7, { type: 'imperial_us' });// Returns: "-11 mi"
// UK Imperial formattingformatDistance(2, { type: 'imperial_uk' });// Returns: "2 yd"
formatDistance(150.88, { type: 'imperial_uk' });// Returns: "170 yd"
formatDistance(4344.3, { type: 'imperial_uk' });// Returns: "2¾ mi"
formatDistance(21753.68, { type: 'imperial_uk' });// Returns: "14 mi"
// Custom unit labelsformatDistance(1500, { type: 'metric', kilometers: 'KM' });// Returns: "1.5 KM"
// Route distanceconst route = await calculateRoute({ /* ... */ });const distance = formatDistance(route.routes[0].summary.lengthInMeters);console.log(`Total distance: ${distance}`);// Output: "Total distance: 45 km"Parameters:
meters– The distance in metersoptions– Optional display units configurationtype– Unit system:'metric','imperial_us', or'imperial_uk'meters,kilometers,feet,yards,miles– Custom unit labels
Returns: string – Formatted distance string (empty string if input is null/undefined).
Global Configuration
You can set default display units globally using TomTomConfig:
import { TomTomConfig } from '@tomtom-org/maps-sdk/core';
TomTomConfig.instance.put({ apiKey: 'YOUR_API_KEY_HERE', displayUnits: { distance: { type: 'imperial_us', feet: 'ft', miles: 'mi' }, time: { hours: 'hr', minutes: 'min' } }});
// Now all formatting functions will use these defaultsformatDistance(1000); // Uses imperial_usformatDuration(3600); // Uses custom time unitsOptions passed directly to formatting functions will override global configuration.