import config from './../config' import axios from 'axios' import { LatLng } from './common' export interface DistanceMatrixRequestOptions { origins: LatLng[] destinations: LatLng[] departureTime?: number | string mode?: string debug?: boolean context?: string } export interface DistanceMatrixResponse { status: string rows: Array } interface DistanceMatrixResponseRow { elements: Array } interface DistanceMatrixResponseElement { duration: { value: number } raw_duration: { value: number } predicted_duration: { value: number } distance: { value: number } } export const requestDistanceMatrix = async ( opt: DistanceMatrixRequestOptions, ): Promise => { if (!config.API_KEY) { throw new Error('In order to call the NextBillion.ai API, you must provide a valid API Key.') } if (!config.API_HOST) { throw new Error('An API host is required to make request to NextBillion.ai API.') } if (!Array.isArray(opt.origins) || opt.origins.length === 0) { throw new Error('Invalid origins') } if (!Array.isArray(opt.destinations) || opt.destinations.length === 0) { throw new Error('Invalid destinations') } const params: any = { key: config.API_KEY, origins: opt.origins.map((origin) => `${origin.lat},${origin.lng}`).join('|'), destinations: opt.destinations.map((dest) => `${dest.lat},${dest.lng}`).join('|'), debug: opt.debug || 'false', } if (!opt.departureTime || (typeof opt.departureTime === 'string' && isNaN(parseInt(opt.departureTime)))) { opt.departureTime = 0 } params.departure_time = opt.departureTime if (opt.mode) { params.mode = opt.mode } if (opt.context) { opt.context } return await axios .get(`https://${config.API_HOST}/distancematrix/json`, { params, }) .then((resp) => resp.data as DistanceMatrixResponse) }