Geo Service
← All Guides & Resources • Laravel / PHP Tutorial

Routing & Distance Matrices in Laravel with OSRM v1

Integrate fast, domestic turn-by-turn driving directions, travel durations, and distance calculations into your Laravel application without high per-meter Google fees.

Step 1: Configure Environment Variables

Store your server key securely in your Laravel .env file and map it in config/services.php:

.env
GEO_SERVICE_BASE_URL="https://geo.jerielbenavides.com"
GEO_SERVICE_SERVER_KEY="your-secret-server-key-here"
config/services.php
'geo' => [
    'base_url' => env('GEO_SERVICE_BASE_URL'),
    'server_key' => env('GEO_SERVICE_SERVER_KEY'),
],

Step 2: Create the OSRM Routing Service

Create app/Services/OsrmRoutingService.php. Notice the privacy-first error handling: if an HTTP failure occurs, we log a fixed static message rather than dumping the full URL (which contains coordinates and route points!):

app/Services/OsrmRoutingService.php PHP 8.2+
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class OsrmRoutingService
{
    /**
     * Calculate driving route between two Canadian coordinates.
     * Note: OSRM expects coordinates in {longitude},{latitude} format.
     */
    public function calculateRoute(float $startLon, float $startLat, float $endLon, float $endLat): ?array
    {
        $baseUrl = config('services.geo.base_url');
        $key = config('services.geo.server_key');

        $coordinates = sprintf('%.6f,%.6f;%.6f,%.6f', $startLon, $startLat, $endLon, $endLat);
        $url = "{$baseUrl}/route/v1/driving/{$coordinates}";

        try {
            $response = Http::withToken($key)
                ->timeout(5)
                ->get($url, [
                    'overview' => 'simplified',
                    'steps' => 'true',
                ]);

            if ($response->successful()) {
                $data = $response->json();
                if (($data['code'] ?? '') === 'Ok' && !empty($data['routes'])) {
                    $route = $data['routes'][0];
                    return [
                        'distance_meters' => $route['distance'],
                        'distance_km' => round($route['distance'] / 1000, 2),
                        'duration_seconds' => $route['duration'],
                        'duration_minutes' => round($route['duration'] / 60, 1),
                        'geometry' => $route['geometry'] ?? null,
                    ];
                }
            }

            return null;
        } catch (\Throwable $e) {
            // Privacy best practice: Log fixed message without coordinates or URLs
            Log::error('OSRM route calculation failed.');
            return null;
        }
    }
}

Step 3: Using the Service in a Controller

Calculate estimated driving time and distance for a delivery or bailiff route:

DispatchController.php
use App\Services\OsrmRoutingService;

public function dispatchRoute(OsrmRoutingService $router)
{
    // Toronto Downtown (-79.3832, 43.6532) to Mississauga (-79.6441, 43.5890)
    $route = $router->calculateRoute(-79.3832, 43.6532, -79.6441, 43.5890);

    if (!$route) {
        return response()->json(['error' => 'Route unavailable'], 422);
    }

    return response()->json([
        'distance' => "{$route['distance_km']} km",
        'estimated_time' => "{$route['duration_minutes']} minutes",
    ]);
}

🛡 Why Exception Sanitization Matters in Canada

Default PHP exception handlers dump the entire request URL into log files (e.g. storage/logs/laravel.log). In routing queries, that URL reveals precise trip coordinates (such as a domestic abuse shelter or a legal defendant's residence). Catching exceptions and logging generic messages guarantees compliance with Canadian privacy standards.

Start calculating Canadian routes

Create your account today and test the OSRM v1 endpoint with our self-serve developer tier.