@geoapify/route-planner-sdk

中文文档
2.0.0发布于 2026/03/30MITTypeScriptESM + CJS零依赖近 30 天下载 2515

TypeScript SDK for the Geoapify Route Planner API. Supports route optimization, delivery planning, and timeline visualization in browser and Node.js

原始使用文档
文档目录26 节
  1. Table of Contents
  2. Features
  3. Route Editing Capabilities
  4. Installation
  5. Quick Start
  6. Getting API Key
  7. Import the SDK
  8. Example: Create Shipment / Delivery Task
  9. Example: Create Job Optimization Task
  10. Full Documentation
  11. Modifying Route Results
  12. Strategies
  13. Example: Assign jobs to the agent
  14. Example: Assign shipments to the agent
  15. Example: Remove jobs
  16. Example: Remove shipments
  17. Example: Add new jobs
  18. Example: Add new shipments
  19. Timeline Generation
  20. Features
  21. Example: Generate Placeholder Timeline without Waypoints
  22. Example: Generate Timeline with Optimized Routes
  23. Example: Timeline with Custom Popup and Agent Actions
  24. Timeline Setup Requirements
  25. Useful Links
  26. When to Use

Geoapify Route Optimization SDK

Docs npm version MIT License Migration V1→V2

The Geoapify Route Optimization SDK is a lightweight, dependency-free TypeScript library that simplifies building, executing requests, and modifying results for the Geoapify Route Planner API. It helps you easily implement advanced route optimization and delivery planning in both frontend (browser) and backend (Node.js) environments.

Migration note: V2 was introduced with improved method signatures and expanded route-editor capabilities.
If you are upgrading from V1, follow the migration guide:
Migration from V1 to V2

Delivery Routes Optimization

Table of Contents

Features

The Geoapify Route Optimization SDK provides a modern, dependency-free way to interact with the Geoapify Route Planner API, making it easy to implement complex logistics workflows in both browser and backend environments.

Supported Use Cases:

  • Route optimization
  • Delivery planning
  • Pickup/drop-off scheduling
  • Time-constrained and multi-agent logistics

Developer Convenience:

  • Build and send optimization requests
  • Interpret results (e.g., agent timelines, task sequences)
  • Reassign jobs or shipments between agents
  • Modify planned routes dynamically

Visualization Support:

  • Extract structured timeline and status data for each agent
  • Analyze and display routes and schedules using charts or maps

Route Editing Capabilities

Human-readable actionEditor methodTypical use cases
Move existing jobs to another agentassignJobs()
  • Driver calls in sick and jobs must be reassigned.
  • Urgent jobs are moved to a nearby agent.
  • Workload is balanced between two agents during the day.
  • Dispatcher applies manual override after optimization.
Move existing shipments (pickup+delivery) to another agentassignShipments()
  • Reassign a full order when a vehicle is delayed.
  • Move temperature-sensitive shipments to an equipped vehicle.
  • Recover from route disruptions.
Remove jobs from active plansremoveJobs()
  • Customer cancels appointment.
  • Stop is postponed to next day.
Remove shipments from active plansremoveShipments()
  • Order is canceled after planning.
  • Pickup is not ready yet.
  • Shipment is moved to a later batch.
Add new jobs to existing routeaddNewJobs()
  • Same-day on-demand request arrives.
  • Dispatcher creates a manual task.
  • Inspection/service stop is added mid-shift.
Add new shipments to existing routeaddNewShipments()
  • New pickup+dropoff request comes in live.
  • Priority order is inserted into a running route.
Add or remove schedule delay after a waypointaddDelayAfterWaypoint()
  • Traffic jam causes route delay.
  • Loading dock queue adds waiting time.
  • Service finishes earlier than expected (negative delay).
Manually reorder a stop in one routemoveWaypoint()
  • Dispatcher drag-and-drop resequencing.
  • Prioritize a VIP stop earlier.
Reoptimize one agent routereoptimizeAgentPlan()
  • Clean up route after many manual edits.
  • Include unassigned tasks for one agent.
  • Run strict reoptimization with allowViolations: false.
  • Run relaxed reoptimization with allowViolations: true.
Read current edited snapshotgetModifiedResult()
  • Persist edited plan.
  • Render map/timeline after each edit.
  • Implement undo/redo history in UI.

Installation

Install the SDK from NPM:

npm install @geoapify/route-planner-sdk

Quick Start

Getting API Key

To use the Route Optimization SDK, you need a valid Geoapify API Key.

  1. Go to the Geoapify page.
  2. Sign up for a Geoapify account. No credit card is required.
  3. Use the created by default or create a new API key.

You can start with the Free Plan which includes usage limits suitable for testing and small projects. For commercial use and higher request volumes, consider upgrading your plan.

Import the SDK

import { RoutePlanner, Agent, Job } from "@geoapify/route-planner-sdk";
const planner = new RoutePlanner({ apiKey: "YOUR_API_KEY" });

Or use in HTML:

<script src="./node_modules/@geoapify/route-planner-sdk/dist/index.min.js"></script>
<script>
  const planner = new RoutePlannerSDK.RoutePlanner({ apiKey: "YOUR_API_KEY" });
</script>

Example: Create Shipment / Delivery Task

import { RoutePlanner, Agent, Location, Shipment, ShipmentStep, Avoid } from "@geoapify/route-planner-sdk";

const planner = new RoutePlanner({apiKey: API_KEY});

planner.setMode("drive");

planner.addAgent(new Agent().setStartLocation(44.50485912329202, 40.177547000000004).addTimeWindow(0, 7200));
planner.addAgent(new Agent().setStartLocation(44.50485912329202, 40.177547000000004).addTimeWindow(0, 7200));
planner.addAgent(new Agent().setStartLocation(44.50485912329202, 40.177547000000004).addTimeWindow(0, 7200));

planner.addLocation(new Location().setId("warehouse-0").setLocation(44.5130974, 40.1766863));

planner.addShipment(new Shipment().setId("order-1")
    .setDelivery(new ShipmentStep().setDuration(120).setLocation(44.50932929564537, 40.18686625))
    .setPickup(new ShipmentStep().setDuration(120).setLocationIndex(0)));

planner.addShipment(new Shipment().setId("order-2")
    .setDelivery(new ShipmentStep().setDuration(120).setLocation(44.511160727462574, 40.1816037))
    .setPickup(new ShipmentStep().setDuration(120).setLocationIndex(0)));

planner.addAvoid(new Avoid().setType("tolls"));
planner.addAvoid(new Avoid().addValue(40.50485912329202, 42.177547000000004).setType("locations"));

planner.setTraffic("approximated")
planner.setType("short")
planner.setUnits("metric");
planner.setMaxSpeed(10)

const result = await planner.plan();

Example: Create Job Optimization Task

import { RoutePlanner, Agent, Job } from "@geoapify/route-planner-sdk";

const planner = new RoutePlanner({apiKey: API_KEY});

planner.setMode("drive");

planner.addAgent(new Agent().setStartLocation(44.52566026661482, 40.1877687).addTimeWindow(0, 10800).setEndLocation(44.486653350000005, 40.18298485).setPickupCapacity(10000));
planner.addAgent(new Agent().setStartLocation(44.52244306971864, 40.1877687).addTimeWindow(0, 10800));
planner.addAgent(new Agent().setStartLocation(44.505007387303756, 40.1877687).addTimeWindow(0, 10800).setEndLocation(44.486653350000005, 40.18298485).setPickupCapacity(10000));

planner.addJob(new Job().setDuration(300).setPickupAmount(60).setLocation(44.50932929564537, 40.18686625));
planner.addJob(new Job().setDuration(200).setPickupAmount(20000).setLocation(44.50932929564537, 40.18686625));
planner.addJob(new Job().setDuration(300).setPickupAmount(10).setLocation(44.50932929564537, 40.18686625));
planner.addJob(new Job().setDuration(300).setPickupAmount(0).setLocation(44.50932929564537, 40.18686625));

const result = await planner.plan();

Full Documentation

Looking for full API references, usage examples, and SDK architecture details?

👉 Explore the full documentation here:
https://geoapify.github.io/route-planner-sdk/

Modifying Route Results

You can edit planned routes easily using RoutePlannerResultEditor.

Strategies

The editor supports two main strategies for modifying routes:

StrategyDescriptionAPI Call
reoptimizeFull route re-optimization (default). Best results.Route Planner API
preserveOrderInsert without reordering existing stops. Fast and flexible.Route Matrix API (if no position specified) or None

All regular edit operations (assign*, addNew*, remove*, moveWaypoint, addDelayAfterWaypoint) are soft: the requested change is applied and any constraint issues are stored as violations. For strict route improvement, use reoptimizeAgentPlan(agentIdOrIndex, { allowViolations: false }).

preserveOrder strategy behavior:

  • No position params → Uses Route Matrix API to find optimal insertion point
  • With afterId/afterWaypointIndex → Uses Route Matrix API to optimize insertion after that position
  • With afterId/afterWaypointIndex + append: true → Inserts directly after that position (no API call)
  • With append: true → Appends to end of route (no API call)

Example: Assign jobs to the agent

const routeEditor = new RoutePlannerResultEditor(result);

// Default: full reoptimization (Route Planner API)
await routeEditor.assignJobs('agent-a', ['job-2']);

// Find optimal insertion point (Route Matrix API)
await routeEditor.assignJobs('agent-a', ['job-2'], { strategy: 'preserveOrder' });

// Append to end of route (no API call)
await routeEditor.assignJobs('agent-a', ['job-2'], { 
  strategy: 'preserveOrder', 
  append: true
});

// Optimize insertion after a specific job by ID (Route Matrix API)
await routeEditor.assignJobs('agent-a', ['job-2'], { 
  strategy: 'preserveOrder', 
  afterId: 'job-1' 
});

// Optimize insertion after a specific waypoint by index (Route Matrix API)
await routeEditor.assignJobs('agent-a', ['job-2'], { 
  strategy: 'preserveOrder', 
  afterWaypointIndex: 1  // After first stop
});

let modifiedResult = routeEditor.getModifiedResult();

Example: Assign shipments to the agent

const routeEditor = new RoutePlannerResultEditor(result);
await routeEditor.assignShipments('agent-b', ['shipment-2']);

// Or with strategy
await routeEditor.assignShipments('agent-b', ['shipment-2'], { 
  strategy: 'preserveOrder', 
  append: true
});

let modifiedResult = routeEditor.getModifiedResult();

Example: Remove jobs

const routeEditor = new RoutePlannerResultEditor(plannerResult);

// Default: reoptimize remaining route
await routeEditor.removeJobs(['job-2']);

// Remove without reordering remaining jobs
await routeEditor.removeJobs(['job-2'], { strategy: 'preserveOrder' });

let modifiedResult = routeEditor.getModifiedResult();

Example: Remove shipments

const routeEditor = new RoutePlannerResultEditor(plannerResult);
await routeEditor.removeShipments(['shipment-4']);

// Or with preserveOrder strategy
await routeEditor.removeShipments(['shipment-4'], { strategy: 'preserveOrder' });

let modifiedResult = routeEditor.getModifiedResult();

Example: Add new jobs

let newJob = new Job()
    .setLocation(44.50932929564537, 40.18686625)
    .setPickupAmount(10)
    .setId("job-5");

// Default: reoptimize
await routeEditor.addNewJobs('agent-A', [newJob]);

// Or append to end of route
await routeEditor.addNewJobs('agent-A', [newJob], { 
  strategy: 'preserveOrder', 
  append: true
});

let modifiedResult = routeEditor.getModifiedResult();

Example: Add new shipments

let newShipment = new Shipment()
    .setPickup(new ShipmentStep().setLocation(44.50932929564537, 40.18686625).setDuration(1000))
    .setDelivery(new ShipmentStep().setLocation(44.50932929564537, 40.18686625))
    .addRequirement('heavy-items')
    .setId("shipment-5");

await routeEditor.addNewShipments('agent-A', [newShipment]);

// Or with strategy
await routeEditor.addNewShipments('agent-A', [newShipment], { strategy: 'preserveOrder' });

let modifiedResult = routeEditor.getModifiedResult();

Timeline Generation

RoutePlannerTimeline generates a visual timeline for delivery routes, agents, waypoints, and jobs. It can display either the planned input data or the computed solution, supporting both time-based and distance-based views.

Timeline example

Features

  • Visualizes agent timelines for delivery or pickup tasks
  • Supports "time" or "distance" modes
  • Customizable agent colors, labels, and capacity units
  • Optional waypoint popup details and three-dot agent menus

Example: Generate Placeholder Timeline without Waypoints

Creates an empty placeholder timeline based solely on the input data — no routing solution is computed, and no waypoints are included:


const container = document.getElementById('timeline-container');

new RoutePlannerTimeline(container, inputData, undefined, {
      timelineType: 'time',
      hasLargeDescription: false,
      capacityUnit: 'liters',
      agentLabel: 'Truck',
      label: "Simple delivery route planner",
      description: "Deliver ordered items to customers within defined timeframe",
      agentColors: ["#ff4d4d", "#1a8cff", "#00cc66", "#b300b3", "#e6b800", "#ff3385",
        "#0039e6", "#408000", "#ffa31a", "#990073", "#cccc00", "#cc5200", "#6666ff", "#009999"],
    }
);

You can first generate an empty placeholder timeline and later initialize it using the setResult() function with the routing result data

Example: Generate Timeline with Optimized Routes

Displays a complete timeline that includes the computed routing results, along with interactive waypoint popups for each stop.

const container = document.getElementById('timeline-container');

new RoutePlannerTimeline(container, inputData, result, {
        timelineType: 'time',
        hasLargeDescription: false,
        capacityUnit: 'liters',
        agentLabel: 'Truck',
        label: "Simple delivery route planner",
        description: "Deliver ordered items to customers within defined timeframe",
        showWaypointPopup: true,
        agentColors: ["#ff4d4d", "#1a8cff", "#00cc66", "#b300b3", "#e6b800", "#ff3385",
          "#0039e6", "#408000", "#ffa31a", "#990073", "#cccc00", "#cc5200", "#6666ff", "#009999"],
      }
);

Example: Timeline with Custom Popup and Agent Actions

import {
  RoutePlannerTimeline,
  Waypoint,
  TimelineMenuItem
} from "@geoapify/route-planner-sdk";

const toPrettyTime = (seconds: number): string => `${Math.floor(seconds / 60)} min`;
const timeLabels = [
  { position: "25%", label: "1h" },
  { position: "50%", label: "2h" },
  { position: "75%", label: "3h" }
];
const agentVisibilityState: boolean[] = [];

const customWaypointPopupGenerator = (waypoint: Waypoint): HTMLElement => {
  const popupDiv = document.createElement('div');
  popupDiv.innerHTML = `
    <div style="display: flex; flex-direction: column; gap: 5px;">
      <h4 style="margin: 0">${[...new Set(waypoint.getActions().map(
        action => action.getType().charAt(0).toUpperCase() + action.getType().slice(1))
      )].join(' / ')}</h4>
      <p style="margin: 0">Duration: ${toPrettyTime(waypoint.getDuration()) || 'N/A'}</p>
      <p style="margin: 0">Time Before: ${toPrettyTime(waypoint.getStartTime()) || 'N/A'}</p>
      <p style="margin: 0">Time After: ${toPrettyTime(waypoint.getStartTime() + waypoint.getDuration()) || 'N/A'}</p>
    </div>`;
  return popupDiv;
};

const agentActions: TimelineMenuItem[] = [
  {
    key: 'show-hide-agent',
    label: 'Hide Route',
    callback: (agentIndex: number) => {
      console.log(`Agent ${agentIndex} visibility toggled`);
    }
  },
  {
    key: 'second-button',
    label: 'Test Button',
    disabled: false,
    hidden: false,
    callback: (agentIndex: number) => {
      console.log(`Agent ${agentIndex} test button clicked`);
    }
  }
];

const container = document.getElementById('timeline-container');

const timeline = new RoutePlannerTimeline(container, inputData, undefined, {
  timelineType: 'time',
  hasLargeDescription: false,
  capacityUnit: 'liters',
  agentLabel: 'Truck',
  label: 'Simple delivery route planner',
  description: 'Deliver ordered items to customers within defined timeframe',
  timeLabels, // optional
  showWaypointPopup: true,
  waypointPopupGenerator: customWaypointPopupGenerator,
  agentMenuItems: agentActions,
  agentColors: ['#ff4d4d', '#1a8cff', '#00cc66', '#b300b3']
});

// Optional: Listen to hover events
timeline.on('onWaypointHover', (waypoint: Waypoint, agentIndex: number) => {
  console.log('Hovered waypoint:', waypoint, 'Agent:', agentIndex);
});

// Optional: Listen to click events
timeline.on('onWaypointClick', (waypoint: Waypoint, agentIndex: number) => {
  console.log('Clicked waypoint:', waypoint, 'Agent:', agentIndex);
});

// Optional: Modify menu items dynamically before they are shown
timeline.on('beforeAgentMenuShow', (agentIndex: number, actions: TimelineMenuItem[]) => {
  return actions.map(action => {
    if (action.key === 'show-hide-agent') {
      return {
        ...action,
        label: agentVisibilityState[agentIndex] ? 'Show Route' : 'Hide Route'
      };
    }
    return action;
  });
});

Timeline Setup Requirements

  • Include the timeline-specific CSS: ./node_modules/@geoapify/route-planner-sdk/styles/timeline-minimal.css
  • Ensure that your HTML container ('timeline-container') is present and ready to render the timeline
  • Import the necessary types for the timeline feature, such as RoutePlannerInputData and RoutePlannerResult

When to Use

The Geoapify Route Optimization SDK is ideal for:

  • Delivery and logistics platforms
  • Multi-agent job dispatching
  • Shipment planning and optimization
  • Interactive route editing and visualization

Simplify your logistics and delivery operations with automated and flexible route optimization.

版本与发布记录

@geoapify/route-planner-sdk 共发布 26 个版本,首次发布于 2025/03/24;过去 12 个月发布了 1 个版本。

版本发布日期距今
2.0.0latest2026/03/307 个月前
1.1.72025/09/231.1 年前
1.1.62025/08/011.3 年前
1.1.52025/07/291.3 年前
1.1.42025/07/291.3 年前
1.1.32025/07/241.3 年前

关于 @geoapify/route-planner-sdk 的常见问题

@geoapify/route-planner-sdk 是什么?

TypeScript SDK for the Geoapify Route Planner API. Supports route optimization, delivery planning, and timeline visualization in browser and Node.js

如何安装 @geoapify/route-planner-sdk?

在项目目录运行 npm install @geoapify/route-planner-sdk,或使用 pnpm add / yarn add / bun add。

@geoapify/route-planner-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@geoapify/route-planner-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@geoapify/route-planner-sdk 可以商用吗?

@geoapify/route-planner-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@geoapify/route-planner-sdk 的下载量有多少?

根据 npm 官方下载统计,@geoapify/route-planner-sdk 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,515 次,日均约 84 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@geoapify/route-planner-sdk 还在维护吗?

最新版本 2.0.0 发布于 2026/03/30(7 个月前);至今共发布 26 个版本,其中过去 12 个月发布了 1 个;首次发布于 2025/03/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。