地理化路线优化 SDK
这个 地理化路线优化 SDK 是一个轻量级、无依赖性 TypeScript 库,用于简化构建、执行请求并修改结果 地理化路线规划器 API。它帮助您轻松地执行高级 路线优化 以及前端(浏览器)和后端(节点.js)环境中的交付规划.
移徙说明:采用V2时改进了方法签名并扩大了路由编辑能力.
如果您正在从 V1 升级, 请遵循迁移指南 :
从V1到V2的迁移

目录
特征
Geoapify Route Optimation SDK提供了一种现代的,无依赖性的方法,可以与Geoapify Route Optimation SDK进行互动 地理化路线规划器 API,使得在浏览器和后端环境都易于执行复杂的物流工作流程.
支持使用实例数字 :
- 路线优化
- 交付规划
- 接发/投放时间表
- 时间限制和多代理后勤
开发者方便数字 :
- 构建和发送优化请求
- 解释结果(如代理时限、任务序列)
- 重新分派工作或代理人之间的货物
- 动态修改计划路线
可视化支持数字 :
- 提取每个代理人的结构化时间表和状态数据
- 使用图表分析并显示路线和时间表
路由编辑能力
| 人能读取的行动 | 编辑器方法 | 典型使用案例 |
|---|---|---|
| 将已有任务移至其他代理 | assignJobs() |
|
| 将已有的运出( 提取+ 交付) 移至另一个代理 | assignShipments() |
|
| 从活动计划中删除工作 | removeJobs() |
|
| 从现行计划中去除货运 | removeShipments() |
|
| 在现有路由中添加新任务 | addNewJobs() |
|
| 在现有路由中添加新货运 | addNewShipments() |
|
| 路径点后添加或删除调度延迟 | addDelayAfterWaypoint() |
|
| 手动重排一个路由中的一站 | moveWaypoint() |
|
| 重新优化一个代理路线 | reoptimizeAgentPlan() |
|
| 读取当前已编辑快照 | getModifiedResult() |
|
安装
从国家预防机制安装 SDK:
npm install @geoapify/route-planner-sdk
快速启动
获取 API 密钥
要使用路由优化 SDK, 您需要有效的 地理化 API 密钥。 。 。 .
- 转到 地理化页面。 。 。 .
- 注册一个Geoapify账户。 不需要信用卡.
- 使用默认创建的或创建新的 API 密钥 .
你可以从 免费计划 包括适合测试和小型项目的使用限制. 对于商业用途和更高的请求量,考虑更新你的计划.
导入 SDK
import { RoutePlanner, Agent, Job } from "@geoapify/route-planner-sdk";
const planner = new RoutePlanner({ apiKey: "YOUR_API_KEY" });
或在 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>
示例: 创建发货/ 交付任务
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();
示例:创建工作优化任务
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();
完整文档
寻找完整的API参考文献,使用示例,以及SDK架构细节?
👉 在此探索全部文档:
https://geoapify.github.io/route-planner-sdk/ 互联网档案馆的存檔,存档日期2014-12-21
修改路由结果
您可以轻松编辑计划中的路由 RoutePlannerResultEditor。 。 。 .
战略
编辑器支持修改路线的两个主要策略:
| 战略 | 说明 | API 调用 |
|---|---|---|
reoptimize | 完整路由再优化(默认). 最佳结果. | 路由规划器 API |
preserveOrder | 插入时不重排已有的站名 。 快速而灵活. | 路由矩阵 API( 如果没有指定位置) 或 无 |
所有正则编辑操作( I)assign*, (中文(简体) ), addNew*, (中文(简体) ), remove*, (中文(简体) ), moveWaypoint, (中文(简体) ), addDelayAfterWaypoint)为软:
要求的修改被应用,任何限制问题都被作为违反规定行为储存.
严格路线改进,使用 reoptimizeAgentPlan(agentIdOrIndex, { allowViolations: false })。 。 。 .
preserveOrder 策略行为 :
- 无职位参数 − 使用路由矩阵 API 找到最佳插入点
- 使用 Waypoint Index 之后的图像 + 使用路由矩阵 API 优化该位置后的插入
- 与 Waypoint Index + 附录相接: 真 — 直接在该位置后插入( 无 API 呼叫)
- 带有附件:真实 + 路由结束的附录( 无 API 呼叫)
示例: 指派任务给代理
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();
示例:向代理人发运货物
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();
示例:删除任务
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();
示例:删除运出
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();
示例:添加新任务
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();
示例: 添加新运出
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();
时间线生成
RoutePlannerTimeline 生成传送路线、代理、出入口和工作的可视时间表。 它既可以显示计划中的输入数据,也可以显示计算出来的解决方案,支持基于时间和远程的视图.

特征
- 可视化代理交付或接货任务的时间表
- 支持“ 时间” 或“ 距离” 模式
- 可定制的代理颜色、标签和能力单位
- 可选的弹出点细节和 三点代理菜单
示例: 生成没有 Waypoint 的占位符时间线
仅根据输入数据创建空占位符时间线——不计算出路由解决方案,也不包括出处: 1
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"],
}
);
您可以先生成一个空占位符时长, 然后再使用 setResult() 函数与路由结果数据
示例: 以优化路线生成时间线
显示包含计算出路由结果的完整时间表,以及每站的交互式路由点弹出.
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"],
}
);
示例:带有自定义弹出和代理动作的时间线
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;
});
});
时间线设置要求
- 包含特定时间段 CSS :
./node_modules/@geoapify/route-planner-sdk/styles/timeline-minimal.css - 确保您的 HTML 容器 (
'timeline-container')在场,并准备提出时间表 - 导入时间轴特性的必要类型, 如 :
RoutePlannerInputData财务报告和审定财务报表RoutePlannerResult
有用链接
何时使用
这个 地理化路线优化 SDK 为:
- 交付和后勤平台
- 多代理工作调度
- 货运规划和优化
- 互动路线编辑和可视化
以自动化和灵活路由优化的方式简化物流和快递业务.