UNPKG

@geoapify/route-planner-sdk

Version:

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

68 lines (67 loc) 3.28 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { RouteMatrixApiError } from "../../../../../models"; /** * Helper class for Route Matrix API calls. * Used for 1→N and N→1 travel time calculations when finding optimal insertion points. */ export class RouteMatrixHelper { constructor(options, routingOptions) { this.baseUrl = options.baseUrl || 'https://api.geoapify.com'; this.apiKey = options.apiKey; this.routingOptions = routingOptions; } calculateMatrix(sources, targets) { return __awaiter(this, void 0, void 0, function* () { const url = `${this.baseUrl}/v1/routematrix?apiKey=${this.apiKey}`; const response = yield fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mode: this.routingOptions.mode || 'drive', type: this.routingOptions.type, avoid: this.routingOptions.avoid, traffic: this.routingOptions.traffic, max_speed: this.routingOptions.max_speed, units: this.routingOptions.units, sources, targets }) }); if (!response.ok) { throw new RouteMatrixApiError(`Route Matrix API failed: ${response.statusText}`, response.status, response.statusText); } return yield response.json(); }); } calculateTravelTime(from, to) { return __awaiter(this, void 0, void 0, function* () { const matrix = yield this.calculateMatrix([{ location: from }], [{ location: to }]); return matrix.sources_to_targets[0][0].time; }); } calculateTimesToLocation(routeLocations, targetLocation) { return __awaiter(this, void 0, void 0, function* () { const matrix = yield this.calculateMatrix(this.toMatrixLocations(routeLocations), this.toMatrixLocations([targetLocation])); return matrix.sources_to_targets.map(row => row[0].time); }); } calculateTimesFromLocation(sourceLocation, routeLocations) { return __awaiter(this, void 0, void 0, function* () { const matrix = yield this.calculateMatrix(this.toMatrixLocations([sourceLocation]), this.toMatrixLocations(routeLocations)); return matrix.sources_to_targets[0].map(entry => entry.time); }); } toMatrixLocations(locations) { return locations.map(loc => ({ location: loc })); } }