Route Planner API

The Route Planner API is designed to solve route planner tasks of different types:

  • TSP (Travelling Salesman Problem)
  • CVRP (Capacitated VRP)
  • VRPTW (VRP with Time Windows)
  • MDHVRPTW (Multi-depot heterogeneous vehicle VRPTW)
  • PDPTW (Pickup-and-delivery problem with Time Windows)

The API accepts input parameters such as locations, amounts, time frames, etc. The API then returns the optimized order of locations as a result. So the Route Planner helps you to solve delivery and route optimization problems for multiple vehicles.

Here are some popular route optimization scenarios that you can experiment with in the Route Optimization API Playground:

Route Planner API Live Demo



Authenfication and API key

To use the Route Planner API, you'll need an API key. You can register and get a Route Planner API Key for free without a credit card.

We offer a free plan, so there's no need to stress about cost. Start for free and upgrade to a paid plan when the needs of your project increase. For more information on our plans, visit the Pricing page.

How to get Geoapify API key

  1. Register on Geoapify MyProjects page
  2. Create a new project.
  3. Go to the API Keys section. One API key is generated automatically. You can generate multiple API keys per project if required.
  4. Optionally, you can protect the API key by listing allowed IP addresses, HTTP referrers, origins, and CORS.
  5. Choose "Route Planner API" and an API key to generate a URL and programming code.
  6. Press the "Try" button to execute the API call and get the result object example.

API reference: inputs

The Route Planner API works via POST request that accepts input data in the request body. The API parameters define inputs to optimize deliveries of bulk or discrete goods as well as optimizing the scheduling of construction, maintenance, and repair jobs.

Request URL


POST https://api.geoapify.com/v1/routeplanner
HEADERS 'Content-Type: application/json'


Request parameters

Name Description
apiKey your Geoapify API key

Request body parameters

Name Type Description
agents Agent[] An agent represents the resource which route and time should be planned (experts, workers, vehicles)
jobs Job[] The list of jobs that should be done
shipments Shipment[] The list of shipments that should be pick up/delivered. The shipments list is used to describe items that should be picked up from one location and delivered to another location.
locations Location[] The list of locations that can be referenced in jobs and shipments
mode "drive", "truck", "walk", "bicycle" Transportation or travel mode. Possible values: "drive", "truck", "walk", "bicycle"

Note! Every task should contain at least one of the lists - jobs and shipments. A task can contain both shipments and jobs.

Agent object

Name Type Description
start_location [longitude, latitude] Start location represented as an array of coordinates: [longitude, latitude]. Usually is a parking or warehouse location for vehicles, an office or home location for workers.
start_location_index number Index of the start location in the locations list
end_location [longitude, latitude] Optional end location for the agent.
end_location_index number Index of the end location in the locations list
pickup_capacity number For bulky goods shipments only! Amount of bulky goods that could be picked up by the agent.
delivery_capacity number For bulky goods shipments only! Amount of bulky goods that could be delivered by the agent.
capabilities string[] List of the agent capabilities that describe a feature, tool, or knowledge of the agent (vehicle or person). This could be any string values - 'extra-long', ''welding machine, 'electricity'. Agent capabilities should match job requirements.
time_windows [[number, number], ...] Working timeframes that are represented as pairs of relative times in seconds: [[0, 3600]] - available the first hour only, [[0, 14400], [18000, 32400]] - corresponds to 8-hours working day with 1-hour lunchtime.
breaks Break[] More flexible way of specifying breaks and interruptions during the working hours. Each break have a desired duration, and list of time_windows during which it can take place. Route planner will try to choose the optimal time window, that fits best to the agent's route.
id string Optional agent identifier, that can help to identify the agent in results
description string The agent description

Note, the time_windows object contains relative time. The time "0" can correspond to a day start, begin of a working day, or any other time.

Note, in case of bulky goods shipment, the goods to be picked up can't be mixed with the goods to be delivered. You can still use both of the "pickup_capacity" and "delivery_capacity" parameters in the task description, but assume that goods to deliver are in one container and goods to deliver in another container. For example, if an agent has 1000 pickup capacity and 1000 delivery capacity, this will mean that he has 2 containers: one of them contains already 1000 units of goods, another is empty. When at the next job he will deliver 200 units and pickup 100 units, the containers will contain 800 and 100 units - picked up and delivered goods are not mixed up.

Break object

Name Type Description
duration number The break duration in seconds.
time_windows [[number, number], ...] Time ranges during which the break can take place, represented as pairs of relative times in seconds. Examples: [[3600, 7200]] - during the 2nd hour from the beginning of working day, [[14400, 18000], [28800, 32400]] - break can take place betwen 4th and 5th working hour or between 8th and 9th working hour.

Job object

Name Type Description
location [longitude, latitude] The job location.
location_index number Index of the location in the locations list
priority number = 0..100 Job priority. By default is 0. 0 - the lowest priority, 100 - the highest priority. Lower priority jobs may be skipped if there is not enough agents or time to serve all.
duration number The job duration in seconds.
pickup_amount number For bulky goods shipments only! Amount of bulky goods to be picked up.
delivery_amount number For bulky goods shipments only! Amount of bulky goods to be delivered.
requirements string[] List of the job requirements that describe a feature, tool or knowledge that is required to make the job. This can be any string values - 'extra-long', 'welding machine', 'electricity'. Job requirements should match agent capabilities.
time_windows [[number, number], ...] Required timeframes that are represented as pairs of relative times in seconds, for example [[0, 3600]]. An agent will be required to reach job location within the time window. Can be used to influence job visit order.
id string Optional job identifier, that can help to identify the job in results
description string The job description

Shipment object

Name Type Description
id string Required parameter, the unique identifier of a shipment.
pickup Object Pickup parameters.
pickup.location [longitude, latitude] Pickup location.
pickup.location_index number Index of the pickup location in the locations list.
pickup.duration number The pickup duration in seconds.
pickup.time_windows [[number, number], ...] Pickup timeframes that are represented as pairs of relative times in seconds, for example [[0, 3600]]. An agent will be required to reach pickup location within the time window. Can be used to influence pickup order.
delivery Object Pickup parameters.
delivery.location [longitude, latitude] Delivery location.
delivery.location_index number Index of the delivery location in the locations list.
delivery.duration number The delivery duration in seconds.
delivery.time_windows [[number, number], ...] Delivery timeframes that are represented as pairs of relative times in seconds, for example [[0, 3600]]. An agent will be required to reach delivery location within the time window. Can be used to influence delivery order.
requirements string[] List of the shipment requirements that describe a feature, tool or knowledge that is required to pick up or deliver the shipment. This can be any string values - 'extra-long', 'dangerous', . Shipment requirements should match agent capabilities.
priority number = 0..100 Shipment priority. By default is 0. 0 - the lowest priority, 100 - the highest priority. Lower priority shipments may be skipped if there is not enough agents or time to deliver all.
description string The shipment description

Location object

Name Type Description
id string Location unique identifier
location [longitude, latitude] The location coordinates.

Here is an example of a Route Planner API request:

POST https://api.geoapify.com/v1/routeplanner?apiKey=YOUR_API_KEY
Content-Type=application/json

{
   "mode":"drive",
   "agents":[
      {
         "start_location":[
            13.381453755359324,
            52.520666399999996
         ],
         "time_windows":[
            [
               0,
               7200
            ]
         ]
      },
      ...
   ],
   "shipments":[
      {
         "id":"order_1",
         "pickup":{
            "location_index":0,
            "duration":120
         },
         "delivery":{
            "location":[
               13.381175446198714,
               52.50929975
            ],
            "duration":120
         }
      },
      ...
   ],
   "locations":[
      {
         "id":"warehouse-0",
         "location":[
            13.3465209,
            52.5245064
         ]
      }
   ]
}

Response Object

The response contains a GeoJSON FeatureCollection object with a feature of "MultiLineString" type, where every feature represents the agent plan.

Every feature, aka agent plan, contains detailed information about route legs, steps, waypoints corresponding to job locations, and a list of actions to be done by the agent.

Besides, the FeatureCollection object is enriched by the "properties" object, which contains the input parameters and may contain issues that appeared by solving the task.

Route Planner Issues object

Name Type Description
unassignedAgents array list of agents that do not have an execution plan (shipments or jobs)
unassignedJobs array list of jobs that are not assigned to any agent
unassignedShipments array list of shipments that are not assigned to any agent

Feature properties or agent plan object

The feature properties contain information about the agent route and jobs execution:

Name Description
agent_index Index of the corresponding agent in the agents input array
distance Distance in meters for the whole agent route
time Time in seconds, that contains travel time
total_time Total time in seconds, contains travel time and action durations
start_time Start time for the agent
mode Requested transportation or travel mode
actions An array of Actions corresponds to the single steps for the agent.
waypoints An array of Waypoints corresponds to the jobs execution plan.
legs An array of RouteLeg. Each leg represents a route from one waypoint to another.

Action object

Contains single operation information:

Name Description
type Type of the action. Possible values: 'start', 'end', 'pickup', 'delivery'
start_time Execution start time
duration Action duration
shipment_index Index of the shipment in original shipments array
shopment_id Shipment unique identifier
job_index Index of the job in original jobs array
job_id Job unique identifier if specified
waypoint_index Index of the correspinding waypoint

Waypoints

Contains information about a waypoint location and works planned in the location.

Name Description
original_location Original location. An array of the coordinates: [lon, lat]
original_location_index Index of the original location if specified in locations input
original_location_id Identifier of the original location if specified in locations input
location Matched location. An array of the coordinates: [lon, lat]
start_time Actions execution start time, corresponds to arrival time for the waypoint.
duration All actions duration
actions An array of Actions planned for the waypoint
prev_leg_index Route leg that leads to the waypoint
next_leg_index Route leg that leads off the waypoint

RouteLeg object

Contains information about a route between 2 locations.

Name Description
distance Length of the route leg in meters
time Time in seconds for the route leg
steps An array of LegStep. Steps of the route
from_waypoint_index Index of the previous waypoint
to_waypoint_index Index of the next waypoint

LegStep object

Contains information about a separate step of RouteLeg:

Name Description
distance Distance in meters for the step
time Time in seconds for the step
from_index An index of the way start point in the corresponding feature coordinates array
to_index An index of the way end point in the corresponding feature coordinates array

Here is an example of Route Optimization result object:

{
   "type":"FeatureCollection",
   "properties":{
      "mode":"drive",
      "params":{
         "mode":"drive",
         "agents":[...],
         "shipments":[...],
         "locations":[...]
      },
      "issues":{
         "unassigned_shipments":[ 17 ],
         "unassigned_agents": [ 4 ]
      }
   },
   "features":[ ... ]
}

Here is an example of Agent Plan or separate feature of the result:

{
    "geometry":{
      "type":"MultiLineString",
      "coordinates":[...]
    },
    "type":"Feature",
    "properties":{
      "agent_index":0,
      "time":10775,
      "start_time":0,
      "end_time":10775,
      "distance":19203,
      "legs":[
          {
            "time":44,
            "distance":391,
            "from_waypoint_index":0,
            "to_waypoint_index":1,
            "steps":[
                {
                  "from_index":0,
                  "to_index":1,
                  "time":44,
                  "distance":391
                }
            ]
          },
          ...
      ],
      "mode":"drive",
      "actions":[
          {
            "index":0,
            "type":"start",
            "start_time":0,
            "duration":0,
            "waypoint_index":0
          },
          {
            "index":1,
            "type":"pickup",
            "start_time":44,
            "duration":120,
            "shipment_index":19,
            "shipment_id":"order_20",
            "waypoint_index":1
          },
          ...
      ],
      "waypoints":[
          {
            "original_location":[
                13.3908216,
                52.5194189
            ],
            "location":[
                13.390822,
                52.519419
            ],
            "start_time":0,
            "duration":0,
            "actions":[
                {
                  "index":0,
                  "type":"start",
                  "start_time":0,
                  "duration":0,
                  "waypoint_index":0
                }
            ],
            "next_leg_index":0
          },
          ...
      ]
    }
}

Solving VRP-related tasks

The Route Planner is highly customizable, allowing you to solve a wide range of vehicle routing problems. Here are some quick tips and tricks that will simplify defining input parameters.

Bulky goods shipment

The Route Planner API allows planning bulky goods delivery-pickup tasks:

  • Use agent's delivery_capacity / pickup_capacity and job's delivery_amount / pickup_amount
  • It's assumed that agents are loaded at the start location for delivery-related tasks. For example, for the heating oil delivery task a vehicle is full as the start position (the amount is specified in delivery_capacity).
  • It's assumed that agents are empty at the start location for pickup-related tasks and have up to the amount specified in pickup_capacity at the end position.
  • If agents need to perform several iterations to complete all jobs, create additional virtual agents that have their starting position at the end position.

For example, if you have 3 Waste Collector Trucks that can collect 5000l of waste each (15000l in total) and you need to collect 20000l of waste then one of the trucks has to make an additional iteration to complete all jobs. You can create an additional agent that will start from a Waste Recycling Plant (where other agents have the End location). One of the trucks will make the second iteration planned for the additional agent.

Discrete items shipment

Discrete items pickup-delivery is another group of tasks that can be solved with Route Planner API:

  • Use shipments to specify items to deliver / pickup.
  • You can add jobs to the task as well, if to specify some actions.
  • Use locations to add common locations, like storage or warehouse.
  • You can specify capabilities and requirement for agents and jobs to be able complete tasks with special requirements - "extra-long", "fragile", "dangerous".
  • By default, the API optimizes resources (agents). Set agents time-windows to force finish the jobs in the specified time frame.

Resouce management

The Route Planner API lets to manage resources(agents) effectively according to their capabilities and available hours:

  • Use agent's capabilities and job's requirements to specify features, tools, or specific knowledge.
  • Set time_windows for agents and jobs to specify required and available time slots.
  • Don't forget to set job durations for each job.

Modify partially the execution plan

Sometimes it's required to modify the existing Route Plan: add additional jobs or reassign manually some jobs. You can do the easily with capabilities / requirement parameters:

  • Add agent identifier as capability to each agent
  • Add the agent identifier as requirement to each job where an agent is already assigned
  • Solve the task with the new input parameters

Code samples

Visualize agent waypoints

The agent route contains of waypoints or planned jobs and route legs between waypoints. Here is a code sample of how an agent waypoints can be visualized with MapLibre GL / Mapbox GL library:

routePlans.forEach((agentPlan) => {
  const items = agentPlan.waypoints.map((waypoint, index) =>
    point(waypoint.location, { index: index + 1 })
  );

  // create points source + layer
  map.addSource(`waypoints-of-agent-${agentPlan.agentIndex}`, {
    type: "geojson",
    data: featureCollection(items),
  });

  map.addLayer({
    id: `waypoints-of-agent-${agentPlan.agentIndex}`,
    type: "circle",
    source: `waypoints-of-agent-${agentPlan.agentIndex}`,
    paint: {
      "circle-radius": 10,
      "circle-color": color, // set any color here
      "circle-stroke-width": 1,
      "circle-stroke-color": darker_color, // set a darker color here
    },
  });

  map.addLayer({
    id: `waypoints-text-of-agent-${agentPlan.agentIndex}`,
    type: "symbol",
    source: `waypoints-of-agent-${agentPlan.agentIndex}`,
    layout: {
      "text-field": "{index}",
      "text-allow-overlap": false,
      "text-font": ["Roboto", "Helvetica Neue", "sans-serif"],
      "text-size": 12,
    },
    paint: {
      "text-color": textColor, // set contrast to the color textColor
    },
  });
});

Visualize agent route legs

The Route Planner API utilizes Route Matrix API that operates with time and distance values. The API result includes an order of waypoints but not the actual route geometry. Call Routing API with agent waypoint to construct and visualize actual agent route:

routePlans.forEach((agentPlan, index) => {
  const waypoints = agentPlan.waypoints.map(waypoint => waypoint.location as Position);

  generateRoute(waypoints, travelMode /* 'drive', 'truck', ...*/).then((routeData: FeatureCollection) => {
    const layerId = `agent-route-${index}`;
    agentPlan.routeLayer = layerId;
    map.addSource(layerId, {
      type: 'geojson',
      data: routeData as any
    });

    map.addLayer({
      'id': layerId,
      'type': 'line',
      'source': layerId,
      'layout': {
        'line-cap': "round",
        'line-join': "round"
      },
      'paint': {
        'line-color': color
      }
    });
    
    return layerId;
  })
});

function generateRoute(points: Position[], mode: string) {
  const waypoints = points.map(position => position[1] + ',' + position[0]).join('|');
  let url = `https://api.geoapify.com/v1/routing?waypoints=${waypoints}&mode=${mode}&apiKey=${apiKey}`;

  return fetch(url).then((resp) => resp.json());
})

Pricing

Geoapify uses credits as the basis for calculating API call costs. We offer several Pricing Plans based on the number of daily credits you use. Our plans start with a free plan that includes 3000 credits per day. Start for FREE and upgrade as your business grows.

As requires Route Matrix API and Routing API calls inside, the number of credits counted per each API call depends on the number of locations in the input parameters:

  • Agent start locations
  • Agent end locations
  • Shipment pickup and delivery locations
  • Job locations

Below are rules we use for calculating call costs for the Route Planer API:

Rule Cost in credits Example
Number of locations <= 10 NUMBER_OF_LOCATIONS * NUMBER_OF_LOCATIONS 2 delivery boy + 7 pizza orders (2 + 7 ) will cost 9 * 9 = 81 credits
Number of locations > 10 NUMBER_OF_LOCATIONS * 10 7 agents with a start location set + 30 jobs ( 7*2 + 30 = 44 location in total) will cost 44 * 10 = 440 credits

Example 1

The Route Planner task that contains 2 agents with start locations only and 7 jobs (9 locations in total) will cost 9*9 = 81 credits.

Example 2

The Route Planner task that contains 10 agents with start and end locations and 50 jobs (10 * 2 + 50 = 70 locations in total) will cost 70*10 = 700 credits.

Example 3

The Route Planner task that contains 5 agents with start and end locations and 30 shipments (10 * 2 + 30 * 2 = 80 locations in total) will cost 80*10 = 800 credits.