Blog

How to Implement Route Optimization API for Vehicle Fleet Management

9 mins Read

September 13, 2023

Introduction

The efficient handling of vehicle fleets has become more important than ever in the field of modern logistics. Businesses are constantly looking for methods to improve customer happiness, cut fuel costs, increase productivity and optimize processes.

Route optimization is one of the key tactics for achieving these objectives. In this blog, we’ll go in-depth on the function that routes play in managing a fleet of vehicles and emphasize how they affect several operational facets.

We will highlight the significance of identifying the best routes, go into the idea of route optimization, and offer a step-by-step implementation manual for integrating NextBillion.ai’s Route Optimization API into your fleet management procedure.

The Role of Routes in Vehicle Fleet Management

Routes serve as the conduits between a fleet’s activities and its clients. They have the ability to influence customer happiness, driver productivity, fuel costs, and operational efficiency.

Routes that are efficiently planned result in less mileage and fuel usage, which, over time, saves a significant amount of money. In turn, this improves operational effectiveness and gives companies a competitive advantage.

Another important factor that routes influence is driver productivity. Routes that are well-optimized reduce idle time and increase the driver’s capacity to perform more deliveries in a given amount of time.

Smoother operations and improved client relations result from a happier, less stressed driver. The effect of routes also affects consumer satisfaction. Deliveries that are correct and on time are crucial for fostering customer loyalty.

The best routes guarantee that deliveries are made within predetermined time frames, lowering the possibility of delays and improving the customer experience.


Emphasizing the Need for Optimal Routes

Route planning involves finding the optimum route between a starting point and a destination. It involves considering time, distance, traffic, weather, and consumer preferences.

Route planning aims to maximize resource use while minimizing costs, travel time, and obstacles. Transportation, logistics, distribution, and field service management use it to move efficiently between sites.

However, route optimization is a cutting-edge method for improving transport efficiency by precise timing and arranging many stops. It goes beyond picking the shortest path from A to B. Route optimization considers vehicle capacity, load balance, time windows, delivery priority, fuel efficiency, and emissions reduction.

The requirement for route optimization is more important than ever because of these complications.

Understanding Route Optimization

Finding the most effective order of stops for each vehicle in a fleet is known as route optimization. To design routes that enhance efficiency while lowering operational costs, a variety of factors are taken into consideration.

A balance between variables including time, space, truck capacity, and delivery windows is what’s intended. By strategically determining the optimal sequence of stops, route optimization aims to streamline the delivery process, minimize travel distance, and maximize resource utilization.

This not only improves the bottom line for businesses but also contributes to reducing environmental impact by optimizing routes and reducing fuel consumption.

Here are some of the benefits of route optimization:

  • Reduced fuel costs: By optimizing routes, businesses can reduce the total distance traveled by their vehicles, which can save them money on fuel costs.
  • Increased customer satisfaction: By reducing the delivery time, businesses can improve customer satisfaction.
  • Improved efficiency: Route optimization can help businesses to improve the efficiency of their delivery operations, which can free up resources for other tasks.
  • Reduced emissions: By optimizing routes, businesses can reduce the amount of emissions produced by their vehicles, which can help to improve air quality.

Key Features and Variables of Route Optimization API

Several essential features and variables play a significant role in route optimization:

  1. Vehicle Capacity: Optimizing routes requires considering the capacity of each vehicle. Ensuring that vehicles are loaded optimally can lead to fewer trips and increased efficiency.
  2. Time Constraints: Incorporating delivery time windows into route planning ensures that deliveries are made within the preferred time frames of customers.
  3. Multiple Stops: Efficiently organizing routes with multiple stops reduces unnecessary detours and backtracking, thus saving time and resources.
  4. Skills: Optimizing routes requires considering specific abilities or qualifications that a vehicle possesses, i.e., refrigeration, fragile cargo, and heavy loads.
  5. Cost: Optimizing routes requires considering user-defined costs for specific routes.
  6. Relations: Considering relationship between job and the shipment plays a significant role in the route optimization

Integrating NextBillion.ai’s Route Optimization API

The Route Optimization API from NextBillion.ai offers a potent way to improve your fleet management approach. Here’s how to do it successfully:

  1. Setup Vehicle Specifications, Skills, Stops, Cost and Job-Shipment Relationship: Fill out the API with pertinent data regarding delivery locations, skills, and vehicle details.
  2. Post Request: To start the optimization process, send a POST request using the API. The optimization algorithm will analyze the data and give you fleet-specific, optimum routes.
  3. Get Request: To retrieve the results of the Post request using the unique reference ID.

In today’s fast-paced business climate, effective fleet management of vehicles is required to preserve competitiveness. Using technology to optimize routes can lead to improved operational effectiveness, increased customer happiness, and significant cost savings. Learn more about the parameter from our Route Optimization API tutorials

The next sections cover the integration of the NextBillion.ai Route Optimization API into your fleet management system.

Route Optimization Example

In this blog, we have considered a real-time scenario which has,

  1. 4 vehicles with properties like vehicle capacity, skill set, time window, pickup and delivery point.
  2. 4 different jobs
  3. 2 shipments

We have considered the job-shipment relationship as well in route optimization. In this example, we have considered that job 1 should be performed before job 2, and it’s a sequential relationship (job 1 must happen before job 2) The second relation specifies that vehicle 1 should be assigned to job 3, and it’s an assignment relationship.

Furthermore, we have considered the route cost as well, it is the cost associated with different actions or decisions, such as traveling between locations, performing jobs, or using specific vehicles.

Pre-requisites

A few conditions must be met before developing a vehicle fleet management service and using the NextBillion.ai Route Optimization API. These are the essential requirements:

  1. Python Environment: Ensure that Python is installed on your computer. Python can be installed and downloaded from the official website.
  2. Libraries: Ensure that the Requests library is installed on your computer using the Anaconda command prompt using the following command (Conda install requests) or Jupyter Notebook using the following command (!pip install requests) and Flask App.
  3. JSON Data Format: The Route Optimization API accepts and rejects input in JSON format. Make sure you comprehend the JSON syntax and how to parse JSON data.
  4. API Key and Access: By registering on our website, you can get an API key from Nextbillion.ai. In order to access the Route Optimization API, login and authorization are required.
  5. Understanding of RESTful APIs: Know the basics of RESTful APIs, HTTP methods (GET, POST, etc.), request/response formats (JSON), and API authentication (using API keys).

Step-by-Step Integration of Nextbillion.ai’s Route Optimization API

In this section, we will walk you through the steps required to integrate NextBillion.ai’s Route Optimization API into your Python application.

Step 1: Environment Setup

Before we begin, make sure you have the necessary environment set up. We recommend using Jupyter Notebook within Anaconda for this project. Start by installing the requests library using the following command:

!pip install requests

Step 2: Implementing the Route Optimization API

In this step, we’ll import the required modules and define the API URL while preparing the data for the POST request. This data includes locations, jobs, vehicles, and other parameters. Here’s a snippet of the code:

import requests

//Define the API URL
url= "https://api.nextbillion.io/optimization/v2?key=YOUR_API_KEY"

//Prepare the data (locations, jobs, vehicles, etc.)
//The following data can be updated as per your use case.

data= {
"locations": {
"id": 2,
"location": [
"34.06675919,-118.30620984",
"34.04268850,-118.28191077",
"34.03434239,-118.28358834",
"34.04238041,-118.23817754",
"34.08431954,-118.25597762",
"34.06892275,-118.29156827",
"34.01103011,-118.19238067",
"34.08659806,-118.17526366",
"34.06624918,-118.11066669",
"34.05221370,-118.28427087",
],
},
"description": "Fleet Management Scenario",
"jobs": [
{
"id": 1,
"location_index": 0,
"service": 300,
"delivery": [1],
"setup": 200,
"pickup": [],
"time_windows": [[1656327600, 1656342000]],
},
{
"id": 2,
"location_index": 1,
"service": 300,
"delivery": [4],
"pickup": [],
"time_windows": [[1656327600, 1656332000]],
},
{
"id": 3,
"location_index": 2,
"service": 300,
"delivery": [3],
"pickup": [],
"time_windows": [[1656327600, 1656332000]],
},
{
"id": 4,
"location_index": 3,
"service": 300,
"delivery": [2],
"pickup": [],
"time_windows": [[1656327600, 1656332000]],
},],
"vehicles": [
{
"id": 1,
"start_index": 3,
"end_index": 3,
"capacity": [46],
"time_window": [1656327600, 1656372000],
"skills": [1, 2],
},
{
"id": 2,
"start_index": 4,
"end_index": 4,
"capacity": [100],
"time_window": [1656327600, 1656372000],
"skills": [3],
},
{
"id": 3,
"start_index": 2,
"end_index": 2,
"capacity": [56],
"time_window": [1656327600, 1656372000],
"skills": [1, 2, 3],
},
{
"id": 4,
"start_index": 1,
"end_index": 1,
"capacity": [60],
"time_window": [1656327600, 1656372000],
"skills": [2, 3],
},
],
"shipments": [
{
"pickup": {
"id": 1,
"service": 300,
"location_index": 6,
"time_windows": [[1656329600, 1656342000]],
},
"delivery": {
"id": 1,
"service": 300,
"location_index": 3,
"time_windows": [[1656339600, 1656352000]],
},
"pickup": {
"id": 1,
"service": 300,
"location_index": 4,
"time_windows": [[1656329600, 1656342000]],
},
"delivery": {
"id": 1,
"service": 300,
"location_index": 2,
"time_windows": [[1656339600, 1656352000]],
},
"relations": [
{
"type": "sequence",
"jobs": [1, 2],
"sequence_type": "sequential",
},
{
"type": "assignment",
"job": 3,
"vehicle": 1,
},
],
"cost": {
"travel": {
"matrix": [[0, 10, 15, 20, 25, 30, 35, 40, 45, 50],
[10, 0, 10, 15, 20, 25, 30, 35, 40, 45],
[15, 10, 0, 10, 15, 20, 25, 30, 35, 40],
],
},
"job_service": {
"default": 100,
},
"vehicle_use": {
"default": 10,
},
},
"amount": [5],
"skills": [2],
"priority": 100,
},
],
}

//Send a POST request to the API

response=requests.post(url,json=data)

//Check the response status

if response.status_code== 200:
print("Request was successful.")
print("Response:")
print(response.json())

else:
print("Request failed with status code:",response.status_code)
print("Response:")
print(response.text)
  • We define the data that will be sent in the POST request to the API. This data includes various objects such as locations, jobs, vehicles, cost, relations and shipments that will be used for route optimization. Refer to the API documentation for more details of these data objects.
  • Here, we send a POST request to the specified API URL, including the JSON data. We check the HTTP status code of the API response. If it’s 200 (OK), we print a success message along with the JSON response data. Otherwise, we print an error message along with the status code and response text.

API Response

{
'id': 'dd03afb891f620716181b3d7aff4bc89',
'message': 'Optimization job created',
'status': 'Ok',
'warning': [
'location_index[5] and 4others are unused',
'location_index[3] and 3others are used for both pickups/deliveries as well as vehicle start/end'
]
}

The result you received from the API contains important information about the optimization job you requested. Overall, the result indicates that the optimization job creation was successful. Here’s a detailed explanation of each part of the result:

To learn more, consult the API documentation for comprehensive tutorials.

Route Optimization Process

  1. Sending the input data to the optimization library
    The above Python code constructs a JSON payload “Data”, This Data object contains vehicles, skills, cost, jobs, locations and relations. Then a POST request is sent to the NextBillion API along with a URL for fleet route optimization.
  2. Calculation of optimized route
    The optimization is handled by the nextbillion.ai library. The heuristic algorithms will be implemented on the input Data provided in the JSON payload. The algorithm adaptation depends on the scenario and control parameters of the Data.
  3. Customization Options and Parameters
    For better results, the following parameters can be adjusted to influence the optimization process. The variables are vehicle capacity, cost, skills, relations and most importantly priority.

By adjusting these parameters in the JSON payload, you can have control over the fleet management needs.

Step 3: HTML Template for Displaying Results

  • Create a folder structure:
project_folder/
├──app.py
├──templates/
│ └── index.html

Open the flask app and create a new project.

  • HTML Template

To visualize the optimized routes on a map, we’ll create an HTML template (index.html) that uses the Leaflet library. Here’s the HTML code snippet:

<!DOCTYPEhtml>
<html>
<head>
<title>Optimized Routes using Leaflet</title>
<!--Include Leaflet CSS and JS -->
<linkrel="stylesheet"href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<scriptsrc="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<style>
#map {
height: 600px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
varoptimizedRoute= {{optimized_route|tojson}};
// Initialize Leaflet map
varmap =L.map('map').setView([1.2931, 103.8558], 10); // Set your desired center and zoom level

//Adda tile layer (OpenStreetMap)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <ahref="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// Plot optimized routes on the map
varrouteCoordinates=optimizedRoute.map(function(location) {
return[location.latitude,location.longitude];
});
L.polyline(routeCoordinates, { color: 'blue', weight: 5 }).addTo(map);
</script>
</body>
</html>

Step 4: Flask App for Get Requests

To retrieve the optimized results, we’ll create a Flask app that handles GET requests. Users can access the results through a web browser using a specific URL. Here’s the Flask code:

fromflask import Flask, request,render_template
importrequests
app= Flask(__name__)
@app.route("/api/index", methods=["GET"])
defindex():
ifrequest.method== "GET":
url=https://api.nextbillion.io/optimization/v2/result?{id}{api_key}"
response=requests.get(url)
ifresponse.status_code== 200:
optimized_route=response.json()
returnrender_template("index.html",optimized_route=optimized_route)
else:
print("Request failed with status code:",response.status_code)
print("Response:")
print(response.text)
return"Request failed"
else:
returnrender_template("index.html")
if__name__ == "__main__":
app.run(debug=True)

Make sure to replace “your_api_key” and “your_id” with your actual API key and ID.

In the given Flask code, when a user accesses the /api/index endpoint using a web browser, the following steps occur:

  • The Flask route handler (index function) sends a GET request to the NextbillionAI API endpoint to retrieve the route optimization result.
  • The response from the API is parsed, and if the request is successful (HTTP status code 200), the optimized route data is obtained.
  • The Flask render_template function renders the index.html template, passing the optimized_route data as a context variable.

Step 5: Results

To access the Flask app via a web browser, use the following URL  when running the app locally.

http://127.0.0.1:5000/api/index

Note: In a production environment, the IP address and port may change.

route optimization api

Note: This image is for reference only.

Tech Stack

  • Programming Language: Python
  • API Integration: NextBillion.ai’s Route Optimization API
  • Data Format: JSON

Learn how to solve more complex optimization problems from our Route Optimization API tutorials. Reach out us for a live demo

About Author

Jim Welch

Jim Welch is the Head of Solutions Engineering at Nextbillion.ai, where he leads a talented team in delivering scalable mapping and location solutions that drive sales results. With a career spanning over three decades, Jim has an extensive background in multi-objective vehicle route optimization, location-based services (LBS), and cloud-native architectures.

Ready to get started?

Request a Demo

Get routes that need no editing or on-road improvisations

Blog Img

Ready to up your game in scheduling, dispatch, and routing?

Request a Demo