Skip to main content
Route Optimization API: 50 lines code se delivery costs 30 percent
Tutorials

Route Optimization API: 50 lines code se delivery costs 30 percent

Multi-stop delivery routes ko optimize karne, time windows lagane, EU Low Emission Zones se bachne aur 50 lines code mein result ko map par dikhane ke liye MapAtlas

Brent van der Heiden10 min read
#route optimization#delivery route#routing api#last mile delivery#multi-stop route#logistics api

Last-mile delivery किसी भी supply chain का सबसे महंगा हिस्सा है। Industry benchmarks लगातार last-mile costs को total shipping cost का 53% मानते हैं। इसमें सबसे बड़ा नियंत्रणीय variable route efficiency है। एक ड्राइवर जो 15 stops को गलत क्रम में पूरा करता है, वह आवश्यक से 40% अधिक किलोमीटर चला सकता है, fuel burn करता है, vehicle को wear करता है, और delivery time windows को miss करता है जो redelivery fees trigger करते हैं।

Route optimisation अब code में solve करने के लिए एक कठिन समस्या नहीं है। जिसके लिए कभी महंगे specialist logistics software की आवश्यकता थी, वह अब एक API call है। यह tutorial MapAtlas Routing API का उपयोग करके एक complete multi-stop route optimiser बनाता है: एक Python script जो delivery stops की list भेजती है, optimised sequence को total distance और time के साथ वापस पाती है, time window constraints लागू करती है, और urban deliveries के लिए EU Low Emission Zone restrictions को handle करती है। एक JavaScript snippet फिर result को map पर draw करता है।

Python implementation 55 lines से कम है। JavaScript map display additional 30 lines है।

Last-Mile Cost Problem

यह समझने के लिए कि optimization वास्तव में क्या बचाता है, एक realistic delivery scenario के लिए numbers चलाएं:

  • Fleet: 10 vans
  • Stops per van per day: 18
  • Current average distance: 210 km/van/day
  • Fuel cost: €0.38/km (diesel, EU average)
  • Driver cost: €22/hour
  • Average current route time: 7.5 hours/day

Current daily cost per van: (210 × €0.38) + (7.5 × €22) = €79.80 + €165 = €244.80/van/day

30% distance reduction (dense urban network पर अच्छे optimization से achievable) और 20% time saving produce करता है:

  • Optimised distance: 147 km → fuel cost: €55.86
  • Optimised time: 6 hours → driver cost: €132
  • Optimised daily cost per van: €187.86/van/day

Saving per van per day: €56.94। 10 vans के लिए 250 working days में: €142,350/year, एक API integration से।

ऊपर दिए गए benchmarks last-mile logistics studies के real published figures को reflect करते हैं। आपके specific numbers geography, vehicle type, और stop density के अनुसार vary करेंगे। Dense urban areas सबसे बड़े gains देखते हैं क्योंकि naive sequential routes unnecessary backtracking पर सबसे अधिक distance waste करते हैं।

Naive vs Optimised Routes: A Visual Comparison

एक naive (sequential) route और एक optimised route के बीच का अंतर map पर stark है।

Naive routing तब होती है जब आप stops को उसी क्रम में feed करते हैं जिसमें वे enter किए गए थे, पहला customer जिसने order दिया वह route पर first है, geography की परवाह किए बिना। Amsterdam या Berlin जैसे शहर में, यह "spaghetti route" problem create करता है: आपका driver लगातार अपने ही path को cross करता है।

Optimization आपके stop set के लिए Travelling Salesman Problem (TSP) को solve करता है। 15-20 stops के लिए यह computationally tractable है milliseconds में। बड़े fleets के लिए सैकड़ों stops के साथ, vehicle routing problem (VRP) solvers multiple vehicles और capacity limits के additional constraints को handle करते हैं।

Step 1: अपने Delivery Data को Structure करें

प्रत्येक stop को एक location की आवश्यकता है और, time-windowed deliveries के लिए, एक time_window specifying करता है कि delivery कब acceptable है।

import requests
import json

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.mapatlas.eu/v1"

# Depot (start and end point)
depot = {
    "lat": 52.3402,
    "lng": 4.8952,
    "name": "Warehouse - Sloterdijk"
}

# Delivery stops with optional time windows
stops = [
    { "lat": 52.3726, "lng": 4.8971, "name": "Albert Heijn Jordaan",
      "time_window": { "start": "09:00", "end": "12:00" } },
    { "lat": 52.3601, "lng": 4.9123, "name": "Café De Jaren",
      "time_window": { "start": "08:00", "end": "11:00" } },
    { "lat": 52.3780, "lng": 4.8801, "name": "Westergasfabriek Events",
      "time_window": { "start": "10:00", "end": "14:00" } },
    { "lat": 52.3545, "lng": 4.9041, "name": "Hotel V Nesplein",
      "time_window": None },
    { "lat": 52.3620, "lng": 4.8820, "name": "Vondelpark Paviljoen",
      "time_window": { "start": "07:00", "end": "10:00" } }
]

Step 2: Route Optimisation Endpoint को Call करें

Depot और stop list को optimised routing endpoint पर POST करें। API stops को most efficient visit order में return करता है total route distance और duration के साथ।

def optimise_route(depot, stops, vehicle_profile="van-euro6"):
    """
    Request an optimised multi-stop route from the MapAtlas Routing API.
    vehicle_profile options: van-euro6, van-diesel-euro5, electric-van, bike
    """
    waypoints = [
        {
            "lat": s["lat"],
            "lng": s["lng"],
            "name": s["name"],
            **({"time_window": s["time_window"]} if s.get("time_window") else {})
        }
        for s in stops
    ]

    payload = {
        "origin": { "lat": depot["lat"], "lng": depot["lng"] },
        "destination": { "lat": depot["lat"], "lng": depot["lng"] },  # return to depot
        "waypoints": waypoints,
        "optimise": True,
        "vehicle_profile": vehicle_profile,
        "avoid_low_emission_zones": True  # auto-avoids LEZs for non-compliant profiles
    }

    response = requests.post(
        f"{BASE_URL}/routing/optimise",
        json=payload,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        }
    )
    response.raise_for_status()
    return response.json()

result = optimise_route(depot, stops)

Step 3: Optimised Route को Parse और Display करें

API response में optimised order में stops, प्रत्येक stop के लिए cumulative ETAs, total distance, और total duration शामिल है।

def display_route_summary(result):
    route = result["route"]
    print(f"\n--- Optimised Route Summary ---")
    print(f"Total distance : {route['total_distance_km']:.1f} km")
    print(f"Total duration : {route['total_duration_min']:.0f} min")
    print(f"Stops          : {len(route['waypoints'])}\n")

    print(f"  START  {depot['name']}")
    for i, stop in enumerate(route["waypoints"], 1):
        eta     = stop["eta"]
        tw      = stop.get("time_window")
        on_time = "(on time)" if tw and tw["start"] <= eta <= tw["end"] else ""
        print(f"  {i:>2}.   {stop['name']:<35} ETA {eta}  {on_time}")
    print(f"  END    {depot['name']}")

    print(f"\nEstimated fuel saving vs sequential: "
          f"{result.get('saving_vs_naive_km', 0):.1f} km "
          f"({result.get('saving_pct', 0):.0f}%)")

display_route_summary(result)

ऊपर दिए गए पांच stops के लिए Sample output:

--- Optimised Route Summary ---
Total distance : 38.4 km
Total duration : 94 min
Stops          : 5

  START  Warehouse - Sloterdijk
   1.   Vondelpark Paviljoen               ETA 07:48  (on time)
   2.   Café De Jaren                      ETA 08:31  (on time)
   3.   Albert Heijn Jordaan               ETA 09:15  (on time)
   4.   Hotel V Nesplein                   ETA 10:02
   5.   Westergasfabriek Events            ETA 10:44  (on time)
  END    Warehouse - Sloterdijk

Estimated fuel saving vs sequential: 14.2 km (27%)

Step 4: EU Low Emission Zone को Handle करना

Amsterdam का ZTL zone, Paris की Crit'Air system, और Berlin का Umweltzone निर्दिष्ट समय पर निर्दिष्ट vehicle types को central areas से restrict करते हैं। एक route जो distance अकेले पर efficient दिखता है, वह आपके vehicle के लिए invalid हो सकता है।

avoid_low_emission_zones: true parameter vehicle_profile के साथ combined automatically non-compliant vehicles के लिए restricted zones के around routes करता है। Electric और Euro 6 vehicles के लिए, LEZs passable हैं और parameter का कोई प्रभाव नहीं है।

# Example: diesel Euro 5 van, will be re-routed around Amsterdam ZTL
result_euro5 = optimise_route(depot, stops, vehicle_profile="van-diesel-euro5")

# Example: electric van, LEZ restrictions do not apply
result_electric = optimise_route(depot, stops, vehicle_profile="electric-van")

print(f"Euro 5 route distance  : {result_euro5['route']['total_distance_km']:.1f} km")
print(f"Electric route distance: {result_electric['route']['total_distance_km']:.1f} km")
# Electric route will typically be shorter as it can use LEZ-restricted roads

Logistics operations के लिए diesel से electric में transition planning करते हुए, इन दोनों outputs को प्रति route compare करना electrification से available range improvement का direct quantification देता है।

Step 5: Optimised Route को Map पर Display करें

API response से route geometry लें और इसे JavaScript में एक line layer के रूप में render करें।

import mapmetricsgl from '@mapmetrics/mapmetrics-gl';
import '@mapmetrics/mapmetrics-gl/dist/mapmetrics-gl.css';

// routeResult is the parsed API JSON response passed to the frontend
function renderOptimisedRoute(map, routeResult) {
  const { waypoints, geometry, total_distance_km, total_duration_min } = routeResult.route;

  map.on('load', () => {
    // Route line
    map.addSource('optimised-route', { type: 'geojson', data: { type: 'Feature', geometry } });
    map.addLayer({
      id: 'route-line',
      type: 'line',
      source: 'optimised-route',
      layout: { 'line-join': 'round', 'line-cap': 'round' },
      paint: { 'line-color': '#2563EB', 'line-width': 4 }
    });

    // Stop markers with sequence numbers
    waypoints.forEach((stop, i) => {
      const el = document.createElement('div');
      el.textContent = i + 1;
      el.style.cssText = `
        width:28px;height:28px;border-radius:50%;background:#2563EB;color:#fff;
        display:flex;align-items:center;justify-content:center;font-weight:700;
        font-size:13px;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,0.3)
      `;

      new mapmetricsgl.Marker({ element: el })
        .setLngLat([stop.lng, stop.lat])
        .setPopup(
          new mapmetricsgl.Popup().setHTML(`
            <strong>${i + 1}. ${stop.name}</strong>
            <p>ETA: ${stop.eta}</p>
          `)
        )
        .addTo(map);
    });

    // Fit map to route bounds
    const coords = geometry.coordinates;
    const bounds = coords.reduce(
      (b, c) => b.extend(c),
      new mapmetricsgl.LngLatBounds(coords[0], coords[0])
    );
    map.fitBounds(bounds, { padding: 48 });

    // Summary panel
    document.getElementById('route-summary').innerHTML = `
      <strong>${total_distance_km.toFixed(1)} km</strong> ·
      <strong>${total_duration_min.toFixed(0)} min</strong> ·
      ${waypoints.length} stops
    `;
  });
}

const map = new mapmetricsgl.Map({
  container: 'route-map',
  style: 'https://tiles.mapatlas.eu/styles/basic/style.json?key=YOUR_API_KEY',
  center: [4.9041, 52.3676],
  zoom: 12
});

renderOptimisedRoute(map, routeResult);

Calculating Your Real Savings

Once you have the API response in hand, the saving calculation is straightforward. The saving_vs_naive_km field in the response gives you distance saved directly. From that, derive cost savings:

def calculate_savings(result, fuel_cost_per_km=0.38, driver_cost_per_hour=22.0,
                       days_per_year=250, fleet_size=10):
    saving_km    = result.get("saving_vs_naive_km", 0)
    saving_hours = saving_km / 50  # assume 50 km/h average

    daily_fuel_saving   = saving_km * fuel_cost_per_km
    daily_driver_saving = saving_hours * driver_cost_per_hour
    daily_total         = daily_fuel_saving + daily_driver_saving

    annual_fleet_saving = daily_total * days_per_year * fleet_size

    print(f"Distance saved per route : {saving_km:.1f} km")
    print(f"Time saved per route     : {saving_hours * 60:.0f} min")
    print(f"Daily saving (1 vehicle) : €{daily_total:.2f}")
    print(f"Annual saving ({fleet_size} vehicles): €{annual_fleet_saving:,.0f}")

calculate_savings(result)

Time Window Optimisation

Delivering to a bakery at 06:00 and a restaurant at 14:00 while minimising total route distance is a constrained optimisation problem. The API handles this automatically, you only need to provide the windows:

# Time-sensitive stops, the API will schedule these within their windows
stops_with_windows = [
    { "lat": 52.3726, "lng": 4.8971, "name": "Bakery",
      "time_window": { "start": "05:30", "end": "07:00" } },
    { "lat": 52.3620, "lng": 4.8820, "name": "Café",
      "time_window": { "start": "07:00", "end": "09:00" } },
    { "lat": 52.3545, "lng": 4.9041, "name": "Restaurant",
      "time_window": { "start": "13:00", "end": "15:00" } }
]

If any time window constraint cannot be satisfied given the depot departure time and current traffic model, the API returns a constraint_violations array listing which stops could not be reached on time. Your dispatch software can then alert the driver or suggest an earlier departure.

What to Build on Top of This

Route optimisation is the foundation. Once it is running, the natural extensions are:

The Logistics and Delivery industry page and the Fleet Management industry page cover additional MapAtlas features relevant to dispatch software, including multi-vehicle VRP and return-to-depot optimisation.

Getting Started

Frequently Asked Questions

How does route optimisation reduce delivery costs?

Route optimisation reorders multi-stop delivery sequences to minimise total distance and drive time. Studies consistently show 20–35% reductions in distance driven versus a naive sequential route. For a vehicle driving 200 km/day at €0.35/km fuel cost, a 30% reduction saves around €21 per vehicle per day, roughly €5,000 per year per vehicle.

What are time windows in route optimisation?

Time windows are delivery constraints that require a stop to be visited within a specified time range, for example, a business that accepts deliveries only between 09:00 and 12:00. The optimiser must respect all time windows while still minimising total route distance, which is a significantly harder computational problem than unconstrained optimisation.

Does the MapAtlas Routing API handle EU Low Emission Zones?

Yes. The MapAtlas Routing API includes road restriction data for EU Low Emission Zones including Amsterdam's ZTL, the Paris Crit'Air zone, and Berlin's Umweltzone. Pass the vehicle profile (diesel Euro 5, petrol, electric) as a parameter and the router will automatically avoid restricted zones for non-compliant vehicles.

अक्सर पूछे जाने वाले प्रश्न

रूट ऑप्टिमाइज़ेशन डिलीवरी लागत कैसे कम करता है?

रूट ऑप्टिमाइज़ेशन मल्टी-स्टॉप डिलीवरी का क्रम बदलकर कुल दूरी और ड्राइविंग समय को न्यूनतम करता है। अध्ययनों में लगातार पाया गया है कि साधारण क्रमिक रूट की तुलना में २० से ३५ प्रतिशत कम किलोमीटर चलना पड़ता है। जो वाहन प्रतिदिन २०० किमी चलता हो और जिसकी ईंधन लागत ०.३५ EUR प्रति किमी हो, उसमें ३० प्रतिशत की कमी से प्रति वाहन प्रतिदिन लगभग २१ EUR की बचत होती है, यानी प्रति वाहन प्रति वर्ष लगभग ५,००० EUR।

रूट ऑप्टिमाइज़ेशन में टाइम विंडो क्या होते हैं?

टाइम विंडो ऐसी डिलीवरी शर्तें हैं जो यह अनिवार्य करती हैं कि किसी स्टॉप पर एक निर्धारित समय सीमा के भीतर पहुँचा जाए, जैसे कि कोई व्यवसाय जो केवल ०९:०० से १२:०० के बीच डिलीवरी स्वीकार करता हो। ऑप्टिमाइज़र को सभी टाइम विंडो का पालन करते हुए कुल रूट दूरी भी न्यूनतम रखनी होती है, जो बिना किसी प्रतिबंध वाले ऑप्टिमाइज़ेशन की तुलना में काफी कठिन गणनीय समस्या है।

क्या MapAtlas Routing API EU Low Emission Zones को संभालती है?

हाँ। MapAtlas Routing API में EU Low Emission Zones (LEZ) के लिए सड़क प्रतिबंध डेटा शामिल है, जिसमें एम्स्टर्डम की ZTL, पेरिस की Crit'Air ज़ोन और बर्लिन की Umweltzone शामिल हैं। वाहन प्रोफ़ाइल (डीज़ल Euro 5, पेट्रोल, इलेक्ट्रिक) को पैरामीटर के रूप में दें और राउटर स्वचालित रूप से गैर-अनुपालन वाले वाहनों के लिए प्रतिबंधित क्षेत्रों से बचेगा।

यह उपयोगी लगा? इसे साझा करें।

लेखक के बारे में

Brent van der Heiden

लेखक

Brent van der Heiden

Co-Founder & CEO at MapAtlas

Brent built MapAtlas out of a conviction that developers deserve location APIs with fair pricing and genuine end-user privacy. He writes about geospatial infrastructure, AI search visibility, and how location data powers the products people rely on every day.

सभी लेख देखें
ब्लॉग पर वापस जाएं