Reduce delivery times and fuel costs by optimizing routes using Python!
The Challenge of Inefficient Delivery Routes
For logistics companies, e-commerce stores, and delivery services, route optimization is a major factor in reducing costs and improving customer satisfaction. Poorly planned routes lead to:
- Higher fuel expenses
- Increased delivery times
- Overworked drivers
- Dissatisfied customers
Manually planning routes using maps and spreadsheets is inefficient and does not scale as order volumes grow. A Python-based automation system can solve this by calculating the most efficient routes in real time, adjusting dynamically based on traffic, delivery windows, and vehicle capacities.
How Python Automates Route Optimization
Python, combined with powerful libraries like Google OR-Tools, NetworkX, and Geopy, enables businesses to automate route planning. These tools help businesses:
- Optimize multi-stop delivery routes
- Factor in real-time traffic data
- Assign deliveries based on vehicle availability and capacity
- Recalculate routes dynamically when new orders come in
Step 1: Install Required Libraries
pip install ortools geopy pandas
Step 2: Define Locations and Distances
Using Geopy, we can convert addresses into latitude and longitude and then calculate distances between points.
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
geolocator = Nominatim(user_agent="route_optimizer")
# Example addresses
locations = {
"Warehouse": "1600 Amphitheatre Parkway, Mountain View, CA",
"Customer 1": "1 Infinite Loop, Cupertino, CA",
"Customer 2": "345 Spear St, San Francisco, CA"
}
# Convert addresses to coordinates
coordinates = {name: geolocator.geocode(address) for name, address in locations.items()}
# Calculate distance between warehouse and Customer 1
distance = geodesic(
(coordinates["Warehouse"].latitude, coordinates["Warehouse"].longitude),
(coordinates["Customer 1"].latitude, coordinates["Customer 1"].longitude)
).km
print(f"Distance from warehouse to Customer 1: {distance:.2f} km")
Step 3: Optimize Route Using OR-Tools
Google OR-Tools can find the most efficient route for multiple deliveries.
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
# Distance matrix example
distance_matrix = [
[0, 10, 20], # Warehouse to others
[10, 0, 15], # Customer 1 to others
[20, 15, 0], # Customer 2 to others
]
def create_data_model():
data = {}
data["distance_matrix"] = distance_matrix
data["num_vehicles"] = 1
data["depot"] = 0 # Warehouse as starting point
return data
def optimize_route():
data = create_data_model()
manager = pywrapcp.RoutingIndexManager(len(data["distance_matrix"]), data["num_vehicles"], data["depot"])
routing = pywrapcp.RoutingModel(manager)
def distance_callback(from_index, to_index):
return data["distance_matrix"][manager.IndexToNode(from_index)][manager.IndexToNode(to_index)]
transit_callback_index = routing.RegisterTransitCallback(distance_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
solution = routing.SolveWithParameters(search_parameters)
if solution:
print("Optimized Route:")
index = routing.Start(0)
while not routing.IsEnd(index):
print(manager.IndexToNode(index), end=" -> ")
index = solution.Value(routing.NextVar(index))
print(manager.IndexToNode(index))
optimize_route()
Step 4: Real-Time Traffic Adjustments
By integrating APIs like Google Maps or OpenRouteService, real-time traffic data can be incorporated into routing calculations. This allows companies to avoid traffic jams and reroute deliveries dynamically.
import requests
API_KEY = "YOUR_GOOGLE_MAPS_API_KEY"
origin = "1600 Amphitheatre Parkway, Mountain View, CA"
destination = "1 Infinite Loop, Cupertino, CA"
url = f"https://maps.googleapis.com/maps/api/distancematrix/json?origins={origin}&destinations={destination}&key={API_KEY}"
response = requests.get(url)
data = response.json()
print(f"Real-time travel time: {data['rows'][0]['elements'][0]['duration']['text']}")
Business Impact of Automated Route Optimization
Using Python-based automation, businesses can:
✅ Reduce fuel costs by 15-30%
✅ Improve delivery speed by optimizing routes dynamically
✅ Enhance customer satisfaction with accurate ETAs
✅ Scale efficiently without increasing operational workload
Let’s Optimize Your Logistics!
Want to automate your delivery routes and cut down costs? My consulting services specialize in building Python-based logistics solutions tailored to your business needs.
Book a consultation today, and let’s optimize your operations!

Lillqvist Strat consults on business developement, software projects, automation, SOPs, analytical tools and more.
Contact me today to get started on our journey to higher profits, more revenue and happier employees!
Go to Contact now