Ola Map SDK

Routing API

Complete guide to routing, directions, distance matrices, and route optimization

Routing API

The Routing API provides comprehensive routing capabilities including turn-by-turn directions, distance calculations, and route optimization.

Overview

The Routing API includes:

  • Get Directions - Turn-by-turn directions with traffic
  • Directions Basic - Simple routing without traffic
  • Distance Matrix - Calculate distances between multiple points
  • Route Optimizer - Optimize waypoint order
  • Fleet Planner - Multi-vehicle route planning

Get Directions

Get detailed turn-by-turn directions between locations.

Basic Usage

const route = await client.routing.getDirections(
    { lat: 12.993103, lon: 77.543326 },  // Origin
    { lat: 12.972006, lon: 77.580085 }   // Destination
);

With Options

const route = await client.routing.getDirections(
    { lat: 12.993103, lon: 77.543326 },
    { lat: 12.972006, lon: 77.580085 },
    {
        mode: 'driving',           // Travel mode
        steps: true,               // Include turn-by-turn steps
        overview: 'full',          // Full geometry
        traffic_metadata: true,    // Include traffic info
        language: 'en',            // Language
        alternatives: true         // Show alternative routes
    }
);

With Waypoints

const route = await client.routing.getDirections(
    { lat: 12.993103, lon: 77.543326 },
    { lat: 12.972006, lon: 77.580085 },
    {
        waypoints: [
            { lat: 12.980000, lon: 77.550000 },
            { lat: 12.975000, lon: 77.570000 }
        ]
    }
);

Parameters

ParameterTypeRequiredDescription
originobjectYesStarting point { lat, lon }
destinationobjectYesEnding point { lat, lon }
options.modestringNoTravel mode: driving, walking, bicycling, transit
options.stepsbooleanNoInclude turn-by-turn steps (default: true)
options.overviewstringNoGeometry detail: full, simplified, false
options.traffic_metadatabooleanNoInclude traffic information
options.languagestringNoLanguage code (default: en)
options.alternativesbooleanNoReturn alternative routes
options.waypointsarrayNoArray of intermediate points
options.route_preferencestringNoRoute preference: fastest, shortest

Response Structure

{
    status: "OK",
    routes: [
        {
            summary: "NH44 and Outer Ring Road",
            legs: [
                {
                    distance: { text: "8.5 km", value: 8500 },
                    duration: { text: "25 mins", value: 1500 },
                    duration_in_traffic: { text: "32 mins", value: 1920 },
                    start_location: { lat: 12.993103, lng: 77.543326 },
                    end_location: { lat: 12.972006, lng: 77.580085 },
                    steps: [
                        {
                            html_instructions: "Head <b>east</b> on <b>Main Rd</b>",
                            distance: { text: "0.5 km", value: 500 },
                            duration: { text: "2 mins", value: 120 },
                            start_location: { lat: 12.993103, lng: 77.543326 },
                            end_location: { lat: 12.993500, lng: 77.548000 },
                            maneuver: "turn-right"
                        }
                        // ... more steps
                    ]
                }
            ],
            overview_polyline: { points: "encoded_polyline_string" },
            bounds: {
                northeast: { lat: 12.993500, lng: 77.580085 },
                southwest: { lat: 12.972006, lng: 77.543326 }
            }
        }
    ]
}

Get Directions Basic

Get simple directions without traffic information.

const route = await client.routing.getDirectionsBasic(
    { lat: 12.993103, lon: 77.543326 },
    { lat: 12.972006, lon: 77.580085 },
    {
        steps: true,
        overview: 'full',
        language: 'en'
    }
);

Distance Matrix

Calculate travel distances and times between multiple origins and destinations.

Basic Usage

const matrix = await client.routing.getDistanceMatrix(
    '12.993,77.543|12.972,77.580',  // Origins (pipe-separated)
    '12.935,77.615',                 // Destinations (pipe-separated)
    { mode: 'driving' }
);

Multiple Destinations

const matrix = await client.routing.getDistanceMatrix(
    '12.993,77.543|12.972,77.580',
    '12.935,77.615|12.950,77.600|12.960,77.590',
    {
        mode: 'driving',
        route_preference: 'fastest'
    }
);

Parameters

ParameterTypeRequiredDescription
originsstringYesPipe-separated origin coordinates
destinationsstringYesPipe-separated destination coordinates
options.modestringNoTravel mode (default: driving)
options.route_preferencestringNoRoute preference

Response Example

{
    status: "OK",
    origin_addresses: ["Origin Address 1", "Origin Address 2"],
    destination_addresses: ["Dest Address 1", "Dest Address 2"],
    rows: [
        {
            elements: [
                {
                    status: "OK",
                    distance: { text: "5.2 km", value: 5200 },
                    duration: { text: "15 mins", value: 900 }
                },
                {
                    status: "OK",
                    distance: { text: "7.8 km", value: 7800 },
                    duration: { text: "22 mins", value: 1320 }
                }
            ]
        }
    ]
}

Distance Matrix Basic

Simplified distance matrix without advanced options.

const matrix = await client.routing.getDistanceMatrixBasic(
    '12.993,77.543',
    '12.935,77.615'
);

Route Optimizer

Optimize the order of multiple waypoints for the most efficient route.

Basic Usage

const optimized = await client.routing.routeOptimizer(
    '12.993,77.543|12.972,77.580|12.935,77.615',
    {
        source: 'first',      // Start from first location
        destination: 'last',  // End at last location
        mode: 'driving'
    }
);

Round Trip

const optimized = await client.routing.routeOptimizer(
    '12.993,77.543|12.972,77.580|12.935,77.615|12.950,77.600',
    {
        round_trip: true,     // Return to starting point
        mode: 'driving',
        steps: true,
        traffic_metadata: true
    }
);

Parameters

ParameterTypeRequiredDescription
locationsstringYesPipe-separated coordinates
options.sourcestringNofirst, any (default: first)
options.destinationstringNolast, any (default: last)
options.round_tripbooleanNoReturn to start (default: false)
options.modestringNoTravel mode
options.stepsbooleanNoInclude turn-by-turn steps
options.traffic_metadatabooleanNoInclude traffic data

Response Example

{
    status: "OK",
    optimized_order: [0, 2, 1, 3],
    route: {
        legs: [...],
        total_distance: { text: "25.3 km", value: 25300 },
        total_duration: { text: "1 hour 15 mins", value: 4500 }
    }
}

Fleet Planner

Advanced multi-vehicle route planning and optimization.

Basic Usage

const inputData = {
    packages: [
        {
            id: "pkg1",
            location: { lat: 12.993, lon: 77.543 },
            demand: 1,
            time_window: { start: "09:00", end: "17:00" }
        },
        {
            id: "pkg2",
            location: { lat: 12.972, lon: 77.580 },
            demand: 2,
            time_window: { start: "10:00", end: "16:00" }
        }
    ],
    vehicles: [
        {
            id: "v1",
            start_location: { lat: 12.935, lon: 77.615 },
            end_location: { lat: 12.935, lon: 77.615 },
            capacity: 10,
            available_time: { start: "08:00", end: "18:00" }
        }
    ]
};

const result = await client.routing.fleetPlanner(inputData, 'optimal');

With File Input

For large datasets, use a JSON file:

const result = await client.routing.fleetPlanner(
    './data/deliveries.json',  // Path to JSON file
    'optimal',
    { route_preference: 'fastest' }
);

Parameters

ParameterTypeRequiredDescription
inputDataobject/stringYesPackage and vehicle data or file path
strategystringYesOptimization strategy: optimal, fast
options.route_preferencestringNoRoute preference

Response Structure

{
    status: "OK",
    solution: {
        routes: [
            {
                vehicle_id: "v1",
                stops: [
                    {
                        package_id: "pkg1",
                        arrival_time: "09:15",
                        departure_time: "09:20"
                    }
                ],
                total_distance: { text: "15.2 km", value: 15200 },
                total_duration: { text: "45 mins", value: 2700 }
            }
        ],
        unassigned_packages: [],
        statistics: {
            total_vehicles_used: 1,
            total_distance: { text: "15.2 km", value: 15200 },
            total_time: { text: "45 mins", value: 2700 }
        }
    }
}

Travel Modes

The SDK supports multiple travel modes:

Driving

const route = await client.routing.getDirections(
    origin, destination,
    { mode: 'driving' }
);

Walking

const route = await client.routing.getDirections(
    origin, destination,
    { mode: 'walking' }
);

Bicycling

const route = await client.routing.getDirections(
    origin, destination,
    { mode: 'bicycling' }
);

Transit

const route = await client.routing.getDirections(
    origin, destination,
    { mode: 'transit' }
);

Error Handling

Handle routing errors gracefully:

try {
    const route = await client.routing.getDirections(origin, destination);
    console.log(`Distance: ${route.routes[0].legs[0].distance.text}`);
    console.log(`Duration: ${route.routes[0].legs[0].duration.text}`);
} catch (error) {
    if (error.message.includes('No route found')) {
        console.error('No route available between these points');
    } else {
        console.error('Routing error:', error.message);
    }
}

Real-World Examples

Delivery Route Planning

async function planDeliveryRoute(packages, depotLocation) {
    // Build locations string
    const locations = [depotLocation, ...packages.map(p => p.location)]
        .map(loc => `${loc.lat},${loc.lon}`)
        .join('|');
    
    // Optimize route
    const optimized = await client.routing.routeOptimizer(locations, {
        source: 'first',
        destination: 'last',
        mode: 'driving',
        round_trip: true
    });
    
    return optimized;
}

// Usage
const packages = [
    { location: '12.972,77.580', address: 'Customer A' },
    { location: '12.935,77.615', address: 'Customer B' },
    { location: '12.950,77.600', address: 'Customer C' }
];

planDeliveryRoute(packages, '12.993,77.543')
    .then(route => console.log('Optimized route:', route))
    .catch(console.error);

Calculate Delivery Times

async function calculateDeliveryTimes(warehouse, customers) {
    const origins = `${warehouse.lat},${warehouse.lon}`;
    const destinations = customers
        .map(c => `${c.lat},${c.lon}`)
        .join('|');
    
    const matrix = await client.routing.getDistanceMatrix(
        origins, destinations,
        { mode: 'driving' }
    );
    
    return matrix.rows[0].elements.map((element, index) => ({
        customer: customers[index],
        distance: element.distance.text,
        duration: element.duration.text,
        eta: new Date(Date.now() + element.duration.value * 1000)
    }));
}

Compare Routes with Traffic

async function compareRoutes(origin, destination) {
    const [withTraffic, withoutTraffic] = await Promise.all([
        client.routing.getDirections(origin, destination, {
            traffic_metadata: true
        }),
        client.routing.getDirectionsBasic(origin, destination)
    ]);
    
    const normalTime = withTraffic.routes[0].legs[0].duration.value;
    const trafficTime = withTraffic.routes[0].legs[0].duration_in_traffic.value;
    const delay = trafficTime - normalTime;
    
    console.log(`Traffic delay: ${Math.round(delay / 60)} minutes`);
}

Best Practices

1. Cache Distance Matrices

const cache = new Map();

async function getCachedDistance(origins, destinations) {
    const key = `${origins}|${destinations}`;
    if (cache.has(key)) {
        return cache.get(key);
    }
    
    const matrix = await client.routing.getDistanceMatrix(origins, destinations);
    cache.set(key, matrix);
    return matrix;
}

2. Batch Requests

For multiple destinations, use distance matrix instead of individual direction requests:

// ❌ Inefficient - Multiple API calls
const promises = destinations.map(dest => 
    client.routing.getDirections(origin, dest)
);

// ✅ Efficient - Single API call
const matrix = await client.routing.getDistanceMatrix(
    originString,
    destinationsString
);

3. Handle Rate Limits

async function makeRequestWithRetry(fn, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await fn();
        } catch (error) {
            if (error.message.includes('429') && i < maxRetries - 1) {
                await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
            } else {
                throw error;
            }
        }
    }
}

Next Steps

On this page