> ## Documentation Index
> Fetch the complete documentation index at: https://docs.solvice.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Distance Matrix Integration

> How the VRP solver uses Solvice Maps to generate precise distance matrices for optimal route planning

# Distance Matrix Integration

The VRP solver integrates with **[Solvice Maps](https://maps.solvice.io)** to generate high-quality distance matrices before optimization begins. This integration ensures that routing solutions are based on real-world travel times and distances rather than simple geographic calculations.

## Why Distance Matrices Matter

Accurate distance and travel time data is fundamental to creating realistic routing solutions:

```mermaid theme={null}
flowchart LR
    subgraph "Input Data"
        A["Job Locations"]
        B["Resource Locations"]
        C["Vehicle Categories"]
    end
    
    subgraph "Solvice Maps"
        D["Distance Matrix Generation"]
        E["Real Road Networks"]
        F["Traffic-Aware Routing"]
    end
    
    subgraph "VRP Solver"
        G["Constraint Evaluation"]
        H["Route Optimization"]
        I["Feasible Solutions"]
    end
    
    A --> D
    B --> D
    C --> D
    D --> G
    E --> D
    F --> D
    G --> I
    H --> I
    
    style A fill:#e1f5fe
    style B fill:#e1f5fe
    style C fill:#e1f5fe
    style D fill:#fff3e0
    style E fill:#fff3e0
    style F fill:#fff3e0
    style G fill:#e8f5e9
    style H fill:#e8f5e9
    style I fill:#e8f5e9
```

Without accurate distance data, optimization would be based on:

* Euclidean (straight-line) distances
* Uniform travel speeds
* No traffic considerations
* No route restrictions

This leads to solutions that look optimal on paper but fail in reality.

## How It Works

### Pre-Processing Phase

Before the VRP solver begins optimization, it analyzes your request to identify all unique locations and generates distance matrices through [Solvice Maps](https://maps.solvice.io):

<Steps>
  <Step title="Location Extraction">
    The solver scans all jobs and resources to create a comprehensive list of unique coordinates that need distance calculations.

    ```json theme={null}
    // Example extracted locations from jobs and resources
    {
      "locations": [
        [4.3517, 50.8503],  // Brussels depot
        [2.3522, 48.8566],  // Paris delivery
        [3.0686, 50.6365],  // Lille pickup
        [1.0952, 49.4431]   // Rouen service
      ]
    }
    ```
  </Step>

  <Step title="Matrix Request Generation">
    Creates optimized distance matrix requests to [Solvice Maps](https://maps.solvice.io), automatically handling:

    * Request splitting for large location sets
    * Vehicle category mapping (CAR, TRUCK, BICYCLE, etc.)
    * Routing engine selection based on data availability
  </Step>

  <Step title="Distance Matrix Creation">
    Generates distance matrices containing:

    * **Durations**: Travel time between all location pairs in seconds
    * **Distances**: Road network distances in meters
    * **Time-dependent data**: Traffic-aware matrices when applicable
  </Step>
</Steps>

## Available Routing Options

The VRP solver provides several options for distance calculation:

### Euclidean vs Real Road Networks

<Tabs>
  <Tab title="Euclidean Distance">
    ```json theme={null}
    {
      "options": {
        "euclidian": true  // Use straight-line distances
      }
    }
    ```

    **When to use:**

    * Fast prototyping and testing
    * Scenarios where road networks don't matter significantly
    * Performance-critical applications with acceptable accuracy trade-offs

    **Characteristics:**

    * Instant calculation
    * No external dependencies
    * Less accurate for real-world scenarios
  </Tab>

  <Tab title="Real Road Networks">
    ```json theme={null}
    {
      "options": {
        "euclidian": false,  // Use real road networks (default)
        "routingEngine": "OSM"  // OpenStreetMap data
      }
    }
    ```

    **When to use:**

    * Production routing applications
    * When route feasibility matters
    * Scenarios requiring accurate travel times

    **Characteristics:**

    * Based on actual road networks
    * Considers route restrictions
    * More processing time but higher accuracy
  </Tab>
</Tabs>

### Routing Engine Selection

The VRP solver supports multiple routing engines through [Solvice Maps](https://maps.solvice.io):

<CodeGroup>
  ```json OpenStreetMap (OSM) theme={null}
  {
    "options": {
      "routingEngine": "OSM"
    }
  }
  ```

  ```json TomTom (with Traffic) theme={null}
  {
    "options": {
      "routingEngine": "TOMTOM"
    }
  }
  ```
</CodeGroup>

**Available Engines:**

* **OSM**: OpenStreetMap data - comprehensive global coverage
* **TOMTOM**: Commercial routing with traffic data for enhanced accuracy

<Info>
  Routing engine selection is typically handled automatically based on your region and requirements. TomTom routing provides traffic-aware matrices that can vary throughout the day.
</Info>

## Traffic-Aware Routing

For time-sensitive routing, the system can leverage traffic data to create time-dependent distance matrices:

### Traffic Multiplier

Simple traffic adjustment for all routes:

```json theme={null}
{
  "options": {
    "traffic": 1.2  // Increase all travel times by 20%
  }
}
```

### Time-Dependent Matrices

Advanced traffic-aware routing uses **SplineMatrix** technology to provide smooth time-dependent travel times:

<Tabs>
  <Tab title="Standard Matrix">
    ```json theme={null}
    // Fixed travel times regardless of departure time
    {
      "durations": [
        [0, 3420, 2100, 4320],    // From Brussels
        [3420, 0, 1800, 2400],    // From Paris  
        [2100, 1800, 0, 3600],    // From Lille
        [4320, 2400, 3600, 0]     // From Rouen
      ]
    }
    ```
  </Tab>

  <Tab title="Time-Dependent Matrix">
    ```json theme={null}
    // Travel times that vary based on departure time
    {
      "time": 8.5,  // 08:30 AM
      "weekSlice": "MIDWEEK",
      "durations": [
        [0, 4200, 2700, 5100],  // Longer times during rush hour
        [4200, 0, 2200, 2900],
        [2700, 2200, 0, 4200],
        [5100, 2900, 4200, 0]
      ]
    }
    ```
  </Tab>
</Tabs>

**Week Slice Categories:**

* **MIDWEEK**: Monday through Friday traffic patterns
* **WEEKEND**: Saturday and Sunday traffic patterns

## Vehicle Categories

Different vehicle types have different routing characteristics:

```json theme={null}
{
  "resources": [
    {
      "name": "delivery_van",
      "category": "CAR"  // Standard vehicle routing
    },
    {
      "name": "freight_truck", 
      "category": "TRUCK"  // Truck-specific routing restrictions
    }
  ]
}
```

**Supported Categories:**

* **CAR**: Standard vehicle routing with full road access
* **TRUCK**: Heavy vehicle routing with restrictions and regulations
* Additional categories available based on regional requirements

## Integration with VRP Solving

The distance data seamlessly integrates with the optimization process:

<AccordionGroup>
  <Accordion title="Constraint Evaluation">
    **Time Window Constraints**: Use real travel times to determine if jobs can be reached within their time windows.

    **Resource Availability**: Factor in actual travel times when evaluating resource shift compatibility.

    **Capacity Planning**: Consider route distances for fuel consumption and range planning.
  </Accordion>

  <Accordion title="Optimization Objectives">
    **Minimize Travel Time**: Optimize based on actual road network travel times instead of straight-line estimates.

    **Minimize Resources**: Balance resource usage against real travel distances.

    **Workload Distribution**: Distribute actual travel time and service time fairly across resources.
  </Accordion>

  <Accordion title="Solution Quality">
    All generated routes are based on realistic distance data ensuring:

    * Routes are physically possible on real road networks
    * Travel time estimates are accurate
    * Vehicle restrictions are respected
  </Accordion>
</AccordionGroup>

## Performance Considerations

### Matrix Size Impact

| Problem Size | Locations | Matrix Pairs | Typical Generation Time |
| ------------ | --------- | ------------ | ----------------------- |
| Small        | \< 50     | 2,500        | \< 2 seconds            |
| Medium       | 50-200    | 40,000       | 5-15 seconds            |
| Large        | 200-500   | 250,000      | 30-60 seconds           |
| Enterprise   | 500+      | 500,000+     | 1-5 minutes             |

<Tip>
  **Performance Optimization Tips:**

  * Use `euclidian: true` for rapid prototyping and testing
  * Enable real routing only for production scenarios
  * Consider geographic clustering for very large problems
  * Monitor matrix generation time as part of total solve time
</Tip>

## Configuration Examples

### Basic Configuration

Most common setup for real-world routing:

```json theme={null}
{
  "jobs": [
    {"name": "delivery_1", "location": [2.3522, 48.8566]},
    {"name": "pickup_1", "location": [3.0686, 50.6365]}
  ],
  "resources": [
    {"name": "van_1", "start": [4.3517, 50.8503], "category": "CAR"}
  ],
  "options": {
    "euclidian": false,       // Use real road networks
    "routingEngine": "OSM"    // OpenStreetMap routing
  }
}
```

### Traffic-Aware Configuration

For time-sensitive routing with traffic considerations:

```json theme={null}
{
  "jobs": [
    {"name": "morning_delivery", "location": [2.3522, 48.8566], 
     "windows": [{"from": "2024-03-15T08:00:00", "to": "2024-03-15T10:00:00"}]},
    {"name": "afternoon_pickup", "location": [3.0686, 50.6365],
     "windows": [{"from": "2024-03-15T14:00:00", "to": "2024-03-15T16:00:00"}]}
  ],
  "resources": [
    {"name": "driver_1", "start": [4.3517, 50.8503]}
  ],
  "options": {
    "euclidian": false,
    "routingEngine": "TOMTOM",  // Traffic-aware routing
    "traffic": 1.1              // Additional 10% buffer
  }
}
```

### Fast Prototyping Configuration

For quick testing and development:

```json theme={null}
{
  "jobs": [...],
  "resources": [...],
  "options": {
    "euclidian": true,    // Fast straight-line distances
    "traffic": 1.0        // No traffic adjustment
  }
}
```

## Error Handling

The VRP solver includes robust fallback mechanisms when distance matrix generation encounters issues:

### Automatic Fallback

If real routing data is unavailable, the system automatically falls back to euclidean calculations:

```json theme={null}
{
  "warnings": [
    "Routing engine unavailable, using euclidean distances as fallback",
    "Some locations may not be reachable via road network"
  ]
}
```

### Validation Checks

Before optimization begins, the system validates:

* All job and resource locations have valid coordinates
* Selected routing engine is available for the request region
* Matrix generation completed successfully
* Fallback options are properly configured

## Best Practices

<Check>
  **Distance Matrix Best Practices:**

  1. **Development**: Use `euclidian: true` for fast iteration and testing
  2. **Production**: Always use real road networks (`euclidian: false`) for accurate results
  3. **Traffic-Sensitive**: Use TomTom routing engine for time-critical deliveries
  4. **Large Problems**: Monitor matrix generation time and consider geographic clustering
  5. **Reliability**: Implement proper error handling for matrix generation failures
  6. **Testing**: Validate solutions with known routes to verify distance accuracy
</Check>

## Real-World Impact

Using [Solvice Maps](https://maps.solvice.io) for distance matrices typically results in:

<CardGroup cols={2}>
  <Card title="Accuracy Improvement" icon="target">
    **20-40% more accurate** travel time estimates compared to euclidean calculations
  </Card>

  <Card title="Route Feasibility" icon="route">
    **Higher solution quality** with routes that work on actual road networks
  </Card>

  <Card title="Traffic Awareness" icon="clock">
    **Better timing** by considering rush hour and traffic patterns
  </Card>

  <Card title="Operational Efficiency" icon="chart-line">
    **Reduced delivery delays** through realistic route planning
  </Card>
</CardGroup>

## Related Topics

<CardGroup cols={2}>
  <Card title="Basic Routing Example" icon="map" href="/guides/vrp/examples/basic-routing-real-distances">
    See distance matrices in practice
  </Card>

  <Card title="Performance Guide" icon="gauge" href="/guides/vrp/concepts/performance-guide">
    Optimize solving performance
  </Card>

  <Card title="Advanced Time Features" icon="clock" href="/guides/vrp/features/advanced-time-features">
    Time-dependent routing capabilities
  </Card>

  <Card title="Constraint System" icon="cog" href="/guides/vrp/concepts/constraint-system">
    How constraints use distance data
  </Card>
</CardGroup>
