import config from './../config' import axios from 'axios' import { LatLng } from './common' export interface DirectionsRequestOptions { origin: LatLng destination: LatLng wayPoints?: LatLng[] mode?: string steps?: boolean departureTime?: number | string session?: string geometry?: string alternatives?: boolean altCount?: number debug?: boolean context?: string } export interface DirectionsResponse { status: string routes: Array } interface DirectionsResponseRoute { distance: number raw_duration?: number predicted_duration?: number duration: number geometry: string start_location?: { latitude: number longitude: number } end_location?: { latitude: number longitude: number } legs: Array } interface DirectionsResponseLeg { distance: { value: number } raw_duration?: { value: 0 } duration: { value: 0 } start_location?: { latitude: number longitude: number } end_location?: { latitude: number longitude: number } steps: Array } interface DirectionsResponseLegStep { geometry: string start_location?: { latitude: number longitude: number } end_location?: { latitude: number longitude: number } } export const requestDirections = async (opt: DirectionsRequestOptions): 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 (!opt.origin.lat && opt.origin.lat !== 0) { throw new Error('Invalid origin lat') } if (!opt.origin.lng && opt.origin.lng !== 0) { throw new Error('Invalid origin lng') } if (!opt.destination.lat && opt.destination.lat !== 0) { throw new Error('Invalid destination lat') } if (!opt.destination.lng && opt.destination.lng !== 0) { throw new Error('Invalid destination lng') } const params: any = { key: config.API_KEY, origin: `${opt.origin.lat},${opt.origin.lng}`, destination: `${opt.destination.lat},${opt.destination.lng}`, steps: opt.steps || 'false', alternatives: opt.alternatives || 'false', altcount: opt.altCount, debug: opt.debug || 'false', } if (Array.isArray(opt.wayPoints)) { const wayPoints = opt.wayPoints.map((point) => `${point.lat},${point.lng}`).join('|') params['waypoints'] = wayPoints } 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.session) { params.session = opt.session } if (opt.geometry) { params.geometry = opt.geometry } if (opt.context) { params.context = opt.context } return await axios .get(`https://${config.API_HOST}/directions/json`, { params, }) .then((resp) => resp.data as DirectionsResponse) }