Skip to content

Commit

Permalink
feat(routes-api): implement Routes API
Browse files Browse the repository at this point in the history
- Added support for Routes API including origin, destination, and intermediate waypoints.
- Added unit and E2E tests for Routes API functionality.
- Updated README.md with usage examples for the Routes API.
  • Loading branch information
Robert Colca committed Aug 28, 2024
1 parent 856be07 commit c015ebe
Show file tree
Hide file tree
Showing 9 changed files with 1,988 additions and 34 deletions.
59 changes: 51 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

Node.js Client for Google Maps Services
=======================================

Expand All @@ -20,20 +21,21 @@ application.
The Node.js Client for Google Maps Services is a Node.js Client library
for the following Google Maps APIs:

- [Directions API]
- [Distance Matrix API]
- [Elevation API]
- [Geocoding API]
- [Places API]
- [Roads API]
- [Time Zone API]
- [Directions API]
- [Distance Matrix API]
- [Elevation API]
- [Geocoding API]
- [Places API]
- [Roads API]
- [Time Zone API]
- [Routes API]

Keep in mind that the same [terms and conditions](https://developers.google.com/maps/terms)
apply to usage of the APIs when they're accessed through this library.

## Attention!

This library is designed for server-side Node.js applications. Attempting to use it client-side, in either the browser or any other environment like React Native, may in some cases work, but mostly will not. Please refrain from reporting issues with these environments when attempting to use them, since **server-side Node.js applications is the only supported environment for this library**. For other environments, try the [Maps JavaScript API], which contains a comparable feature set, and is explicitly intended for use with client-side JavaScript.
This library is designed for server-side Node.js applications. Attempting to use it client-side, in either the browser or any other environment like React Native, may in some cases work, but mostly will not. Please refrain from reporting issues with these environments when attempting to use them, since **server-side Node.js applications is the only supported environment for this library**. For other environments, try the [Maps JavaScript API], which contains a comparable feature set, and is explicitly in...

## Quick Start

Expand All @@ -54,6 +56,8 @@ const {Client} = require("@googlemaps/google-maps-services-js");

Now instantiate the client to make a call to one of the APIs.

### Elevation API Example

```js
const client = new Client({});

Expand All @@ -73,6 +77,43 @@ client
});
```


### Routes API Example

```js
client.routes({
params: {
origin: {
location: {
latLng: { latitude: 37.419734, longitude: -122.0827784 }, // Origin coordinates
},
},
destination: {
location: {
latLng: { latitude: 37.41767, longitude: -122.079595 }, // Destination coordinates
},
},
travelMode: RouteTravelMode.DRIVE,
routingPreference: RoutingPreference.TRAFFIC_AWARE,
computeAlternativeRoutes: false,
routeModifiers: {
avoidTolls: false,
avoidHighways: false,
avoidFerries: false,
},
languageCode: "en-US",
units: RouteUnits.IMPERIAL,
apiKey: { key: process.env.GOOGLE_MAPS_API_KEY },
},
})
.then((r) => {
console.log(r.data.routes[0].legs[0].duration.text);
})
.catch((e) => {
console.log(e.response.data.error_message);
});
```

## Reference Documentation

The generated reference documentation can be found [here](https://googlemaps.github.io/google-maps-services-js/). The TypeScript types are the authoritative documentation for this library and may differ slightly from the descriptions.
Expand Down Expand Up @@ -132,6 +173,7 @@ client
});
```


The primary differences are in the following table.

| Old | New |
Expand Down Expand Up @@ -198,6 +240,7 @@ If you find a bug, or have a feature suggestion, please
[Time Zone API]: https://developers.google.com/maps/documentation/timezone/
[Roads API]: https://developers.google.com/maps/documentation/roads/
[Places API]: https://developers.google.com/places/web-service/
[Routes API]: https://developers.google.com/maps/documentation/routes

[issues]: https://github.com/googlemaps/google-maps-services-js/issues
[contrib]: https://github.com/googlemaps/google-maps-services-js/blob/master/CONTRIBUTING.md
Expand Down
63 changes: 63 additions & 0 deletions e2e/routes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { decodePath } from "../src/util";
import { routes } from "../src/routes";
import {
RouteTravelMode,
RouteUnits,
RoutingPreference,
} from "../src/interfaces/routes";

test("routes should get correct result", async () => {
const params = {
origin: {
location: {
latLng: { latitude: 37.419734, longitude: -122.0827784 }, // Origin coordinates
},
},
destination: {
location: {
latLng: { latitude: 37.41767, longitude: -122.079595 }, // Destination coordinates
},
},
travelMode: RouteTravelMode.DRIVE,
routingPreference: RoutingPreference.TRAFFIC_AWARE,
computeAlternativeRoutes: false,
routeModifiers: {
avoidTolls: false,
avoidHighways: false,
avoidFerries: false,
},
languageCode: "en-US",
units: RouteUnits.IMPERIAL,
apiKey: { key: process.env.GOOGLE_MAPS_API_KEY },
};

const r = await routes({
params: params,
apiKey: { key: process.env.GOOGLE_MAPS_API_KEY },
});

expect(r.config.url).toContain(
"routes.googleapis.com/directions/v2:computeRoutes"
);

expect(r.data.routes[0].legs[0].distanceMeters).toBeGreaterThan(0);
expect(
decodePath(r.data.routes[0].polyline.encodedPolyline)[0].lat
).toBeDefined();
});
8 changes: 8 additions & 0 deletions src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
TextSearchRequest,
NearestRoadsRequest,
SnapToRoadsRequest,
RoutesRequest, // Import RoutesRequest
X_GOOG_MAPS_EXPERIENCE_ID,
defaultAxiosInstance,
} from "./client";
Expand Down Expand Up @@ -261,4 +262,11 @@ describe("client wraps all functions correctly", () => {
client.snapToRoads({} as SnapToRoadsRequest);
expect(mock).toBeCalledWith({}, client["axiosInstance"]);
});

test("client wraps routes correctly", () => {
const routes = require("./routes");
const mock = (routes.routes = jest.fn());
client.routes({} as RoutesRequest);
expect(mock).toBeCalledWith({}, client["axiosInstance"]);
});
});
34 changes: 14 additions & 20 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import { HttpsAgent } from "agentkeepalive";
import { customAdapter } from "./adapter";

// Cannot be `import` as it's not under TS root dir
// Import Routes API
import { RoutesRequest, RoutesResponse, routes } from "./routes";

export const version = require("../package.json").version;
export const defaultHttpsAgent = new HttpsAgent({ keepAlive: true });
export const defaultTimeout = 10000;
Expand Down Expand Up @@ -117,6 +119,7 @@ export interface ClientOptions {
config?: Config;
experienceId?: string[];
}

/**
* Client is a light wrapper around API methods providing shared configuration for Axios
* settings such as retry logic using the default retry-axios settings and gzip encoding.
Expand Down Expand Up @@ -198,28 +201,11 @@ export class Client {
timezone(request: TimeZoneRequest): Promise<TimeZoneResponse> {
return timezone(request, this.axiosInstance);
}

geolocate(request: GeolocateRequest): Promise<GeolocateResponse> {
return geolocate(request, this.axiosInstance);
}
/**
* An example use of this function.
*
* ```javascript
* import { Client } from '@googlemaps/google-maps-services-js';
*
* const args = {
* params: {
* key: '<your-api-key>',
* address: 'Perth 4WD & Commercial Centre',
* }
* };
* const client = new Client();
* client.geocode(args).then(gcResponse => {
* const str = JSON.stringify(gcResponse.data.results[0]);
* console.log(`First result is: ${str}`);
* });
* ```
*/

geocode(request: GeocodeRequest): Promise<GeocodeResponse> {
return geocode(request, this.axiosInstance);
}
Expand Down Expand Up @@ -263,12 +249,18 @@ export class Client {
textSearch(request: TextSearchRequest): Promise<TextSearchResponse> {
return textSearch(request, this.axiosInstance);
}

nearestRoads(request: NearestRoadsRequest): Promise<NearestRoadsResponse> {
return nearestRoads(request, this.axiosInstance);
}

snapToRoads(request: SnapToRoadsRequest): Promise<SnapToRoadsResponse> {
return snapToRoads(request, this.axiosInstance);
}

routes(request: RoutesRequest): Promise<RoutesResponse> {
return routes(request, this.axiosInstance);
}
}

export {
Expand Down Expand Up @@ -304,4 +296,6 @@ export {
TextSearchResponse,
TimeZoneRequest,
TimeZoneResponse,
RoutesRequest,
RoutesResponse,
};
6 changes: 3 additions & 3 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1632,7 +1632,7 @@ export interface SnappedPoint {
* Represents a descriptor of an address.
*
* <p>Please see <a
* href="https://mapsplatform.google.com/demos/address-descriptors/">Address
* href="https://mapsplatform.google.com/demos/address-descriptors/">Address
* Descriptors</a> for more detail.
*/
export interface AddressDescriptor {
Expand Down Expand Up @@ -1706,7 +1706,7 @@ interface Area {
containment: Containment;
}

/**
/**
* An enum representing the relationship in space between the area and the target.
*/
enum Containment {
Expand All @@ -1733,4 +1733,4 @@ interface LocalizedText {
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
languageCode: string;
}
}
Loading

0 comments on commit c015ebe

Please sign in to comment.