# Dispatch Optimized Routes to Geotab

To dispatch the generated routes to the MyGeoTab Web Application, follow these detailed steps. This process involves constructing a POST request from the routes generated by NextBillion.ai’s Route Optimization API and sending it to Geotab.

## Step 1: Extract Relevant Data from NextBillion.ai Result

First, retrieve the optimization result data, including the routes, from the NextBillion.ai API response.

```javascript
const nbaiResult = nbaiOptimizationStatus.data.result;
const routes = nbaiResult.routes;
```

## Step 2: Define Helper Function to Convert Distance to Miles

Create a helper function to convert distances from meters to miles.

```javascript
const convertToMiles = (distance) => distance * 0.00062137;
```

## Step 3: Get Zone IDs from Dropdowns

Retrieve the zone IDs for the start and end locations from dropdown elements.

```javascript
const startZoneId = select1.value;
const endZoneId = select2.value;
```

## Step 4: Construct the POST Request Body

Build the request body for the POST request to dispatch routes to Geotab.

```javascript
const postRequestBody = {
    method: "ADD",
    params: {
        typeName: "Route",
        entity: {
            comment: "GeoTab_Nb_Integration",
            name: routes[0].description,
            routePlanItemCollection: routes[0].steps.map((step, index) => ({
                activeFrom: dtShiftStart2.value,
                activeTo: dtShiftEnd2.value,
                dateTime: dtShiftStart2.value,
                comment: "",
                expectedDistanceToArrival: convertToMiles(step.distance),
                expectedStopDuration: new Date(step.service * 1000).toISOString().substr(11, 8),
                expectedTripDurationToArrival: new Date(step.duration * 1000).toISOString().substr(11, 8),
                sequence: index,
                zone: {
                    id: (index === 0) ? startZoneId : (index === routes[0].steps.length - 1) ? endZoneId : step.description
                }
            })),
            routeType: "Basic",
            startTime: dtShiftStart2.value,
            endTime: dtShiftEnd2.value
        },
        credentials: {
            "database": "geotab_database",
            "sessionId": "session_id",
            "userName": "user_name"
        }
    }
};
```

## Step 5: Convert Request Body to JSON String

Convert the constructed request body to a JSON string for the POST request.

```javascript
const requestBodyJson = JSON.stringify(postRequestBody);
```

## Step 6: Print and Store the Request Body

Print the request body to the console and store it in local storage for further use.

```javascript
console.log("Post Request Body:", requestBodyJson);
tmpRouteObject.setValue(postRequestBody);

// Store the request body in local storage
localStorage.setValue('tmpRouteGeotab', postRequestBody);
```

## Step 7: Trigger the POST Request to Geotab

`send_to_geotab.trigger` is a function that sends the POST request, use it to dispatch the route to Geotab. Handle success and failure responses appropriately.

```javascript
send_to_geotab.trigger({
    onSuccess: function (data) {
        console.log("Routes processed successfully:", data);
    },
    onFailure: function (error) {
        console.error("Error processing routes:", error);
    }
});
```

## Step 8: Send POST Dispatch Request

Here’s an example of how the POST request will look using curl:

```javascript
curl --location 'https://my.geotab.com/apiv1/dispatches' \
--header 'Content-Type: application/json' \
--data '<request body here>'
```

### API Response

```json
{
  "result": "b9",
  "jsonrpc": "2.0"
}
```

By following these steps, you can successfully dispatch the generated routes to the MyGeoTab Web Application.

The following images showcases the routes dispatched to your MyGeotab dashboard for each driver.

![Visualize dispatch optimized routes in MyGeotab web application dashboard](https://static.nextbillion.io/docs-next/integrations/geotab/geotab-routes.webp)

Integrating NextBillion.ai’s Route Optimization API with the GeoTab Web streamlines the process of generating and dispatching optimized routes. This integration enhances operational efficiency by leveraging advanced route optimization capabilities, thus ensuring that drivers follow the most efficient paths for their deliveries.
