Skip to content

Commit

Permalink
Routing directions API
Browse files Browse the repository at this point in the history
  • Loading branch information
iSanjayAchar committed Jul 19, 2024
1 parent 7f7395b commit 2b33917
Show file tree
Hide file tree
Showing 8 changed files with 208 additions and 3 deletions.
3 changes: 2 additions & 1 deletion dev_test/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as dotenv from "dotenv";
dotenv.config();

import "./places";
// import "./places";
import "./routing";
2 changes: 1 addition & 1 deletion dev_test/places.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ const places = new Places(apiKey);

// places.autocomplete("sadsadsadsadsadsdsads").then(console.log).catch(console.error)
// places.geocoding("271").then(console.log).catch(console.error);
places.reverse_geocoding("12.931316595874005", "77.61649243443775").then(console.log).catch(console.error);
places.reverse_geocode("12.931316595874005", "77.61649243443775").then(console.log).catch(console.error);
13 changes: 13 additions & 0 deletions dev_test/routing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {Routing} from "../src";

const apiKey = process.env.OLA_MAPS_API_KEY as string;

const routing = new Routing(apiKey);

routing.direction({
lat: "18.76029027465273",
lng: "73.3814242364375"
}, {
lat: "18.73354223011708",
lng: "73.44587966939002"
}).then(console.log).catch(console.error);
1 change: 1 addition & 0 deletions src/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const ENV: {
autoCompletePath: "/places/{version}/autocomplete",
geoCodingPath: "/places/{version}/geocode",
reverseGeoCodingPath: "/places/{version}/reverse-geocode",
directionPath: "/routing/{version}/directions",
},
};

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./places";
export * from "./routing";
136 changes: 136 additions & 0 deletions src/routing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import { AxiosInstance, AxiosResponse } from "axios";
import { ENV } from "./const";
import { IBaseResponse, IDirectionResult, ILanguage, IVersion } from "./types";
import { httpClientInit } from "./utilities/http-client";

type Coordinates = {
lat: string | number;
lng: string | number;
}

type DirectionOptions = {
"X-Request-Id"?: string;
"X-Correlation-Id"?: string;
waypoints?: Array<[string | number, string | number]>;
alternatives?: boolean;
steps?: boolean;
overview?: "full" | "simplied" | false;
language?: ILanguage;
traffic_metadata?: boolean;
}

export class Routing {
/**
* API key for authentication with the Places service.
* @private
*/
private apiKey = "";

/**
* The API version to use. Defaults to 'v1'.
* @private
*/
private version: IVersion = "v1";

/**
* The Axios instance used for making HTTP requests.
* @private
*/
private httpClient: AxiosInstance = {} as AxiosInstance;

/**
* Creates a new Places client.
* @param apiKey - Your API key for the Places service.
* @param version - (Optional) The API version to use. Defaults to 'v1'.
* @throws {Error} If the API key is missing or invalid.
*/
constructor(
apiKey: string,
version: IVersion = "v1",
) {
if (!apiKey || apiKey.trim() === "") {
throw new Error("API Key is required. Check documentation - https://maps.olakrutrim.com/docs/auth");
}

this.apiKey = apiKey;
this.version = version;
this.init();
}

/**
* Initializes the Places client by setting up the Axios instance and environment variables.
* @private
*/
private init(): void {
const env = ENV[this.version];
process.env.API_VERSION = this.version;

for (const variable in env) {
if (env[variable]) {
process.env[variable] = env[variable];
}
}

this.httpClient = httpClientInit(this.apiKey);
}

/**
* Calculates directions between an origin and destination, with optional parameters.
*
* @async
* @param {Coordinates} origin - An object with `lat` (latitude) and `lng` (longitude) properties representing the starting point.
* @param {Coordinates} destination - An object with `lat` and `lng` properties representing the ending point.
* @param {DirectionOptions} [options] - Optional parameters for customizing the direction request.
* @returns {Promise<IBaseResponse<IDirectionResult>>} A Promise that resolves to a standardized API response containing the direction results.
* @throws {Error} If an error occurs during the API request, the Promise will be rejected with the error.
*/
public async direction(origin: Coordinates, destination: Coordinates, options?: DirectionOptions): Promise<IBaseResponse<IDirectionResult>> {
try {
let path = `${process.env.directionPath}?origin=${origin.lat},${origin.lng}&destination=${destination.lat},${destination.lng}&`;

if (options) {
if (options["X-Correlation-Id"]) {
path += `X-Correlation-Id=${options["X-Correlation-Id"]}&`;
}

if (options["X-Request-Id"]) {
path += `X-Request-Id=${options["X-Request-Id"]}&`;
}

if (options.language) {
path += `language=${options.language}&`;
}

if (typeof options.alternatives === "boolean") {
path += `alternatives=${options.alternatives}&`;
}

if (typeof options.traffic_metadata === "boolean") {
path += `traffic_metadata=${options.traffic_metadata}&`;
}

if (typeof options.steps === "boolean") {
path += `steps=${options.steps}&`;
}

if (typeof options.overview === "boolean" || typeof options.overview === "string") {
path += `overview=${options.overview}&s`;
}

if (options.waypoints) {
path += `waypoints=${options.waypoints.map((points) => points.join(",")).join("|")}&`;
}

}

if (path.endsWith("&") || path.endsWith("?")) {
path = path.slice(0, -1);
}

const {data}: AxiosResponse<IBaseResponse<IDirectionResult>> = await this.httpClient.post(path, "");
return Promise.resolve(data);
} catch (err) {
return Promise.reject(err);
}
}
}
53 changes: 53 additions & 0 deletions src/types/http-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,56 @@ export type IReverseGeocodingResult = {
layer: Array<string>;
}>;
};

export type IDirectionResult = {
status: IStatus;
source_from: string;
geocoded_waypoints: Array<{
geocoder_status: IStatus;
place_id: string;
types: Array<string>;
}>;
routes: Array<{
bounds: Record<string, string | number>;
copyrights: string;
legs: Array<{
distance: number;
readable_distance: string;
duration: string;
readable_duration: string;
start_address: string;
end_address: string;
start_location: {
lat: number;
lng: number;
};
end_location: {
lat: number;
lng: number;
};
steps: Array<{
distance: number;
readable_distance: string;
duration: number;
readable_duration: string;
start_location: {
lat: number;
lng: number;
};
end_location: {
lat: number;
lng: number;
};
instructions: string;
maneuver: string;
bearing_before: number;
bearing_after: number;
}>
}>;
overview_polyline: string;
travel_advisory: string;
summary: string;
warnings: Array<string>;
waypoint_order: Record<string, string>;
}>;
};
2 changes: 1 addition & 1 deletion src/types/language.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export type ILanguage = "en";
export type ILanguage = "en" | "kn" | "hi";

0 comments on commit 2b33917

Please sign in to comment.