Skip to content

Commit c015ebe

Browse files
author
Robert Colca
committed
feat(routes-api): implement Routes API
- 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.
1 parent 856be07 commit c015ebe

9 files changed

+1988
-34
lines changed

README.md

+51-8
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
Node.js Client for Google Maps Services
23
=======================================
34

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

23-
- [Directions API]
24-
- [Distance Matrix API]
25-
- [Elevation API]
26-
- [Geocoding API]
27-
- [Places API]
28-
- [Roads API]
29-
- [Time Zone API]
24+
- [Directions API]
25+
- [Distance Matrix API]
26+
- [Elevation API]
27+
- [Geocoding API]
28+
- [Places API]
29+
- [Roads API]
30+
- [Time Zone API]
31+
- [Routes API]
3032

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

3436
## Attention!
3537

36-
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.
38+
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...
3739

3840
## Quick Start
3941

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

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

59+
### Elevation API Example
60+
5761
```js
5862
const client = new Client({});
5963

@@ -73,6 +77,43 @@ client
7377
});
7478
```
7579

80+
81+
### Routes API Example
82+
83+
```js
84+
client.routes({
85+
params: {
86+
origin: {
87+
location: {
88+
latLng: { latitude: 37.419734, longitude: -122.0827784 }, // Origin coordinates
89+
},
90+
},
91+
destination: {
92+
location: {
93+
latLng: { latitude: 37.41767, longitude: -122.079595 }, // Destination coordinates
94+
},
95+
},
96+
travelMode: RouteTravelMode.DRIVE,
97+
routingPreference: RoutingPreference.TRAFFIC_AWARE,
98+
computeAlternativeRoutes: false,
99+
routeModifiers: {
100+
avoidTolls: false,
101+
avoidHighways: false,
102+
avoidFerries: false,
103+
},
104+
languageCode: "en-US",
105+
units: RouteUnits.IMPERIAL,
106+
apiKey: { key: process.env.GOOGLE_MAPS_API_KEY },
107+
},
108+
})
109+
.then((r) => {
110+
console.log(r.data.routes[0].legs[0].duration.text);
111+
})
112+
.catch((e) => {
113+
console.log(e.response.data.error_message);
114+
});
115+
```
116+
76117
## Reference Documentation
77118

78119
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.
@@ -132,6 +173,7 @@ client
132173
});
133174
```
134175

176+
135177
The primary differences are in the following table.
136178

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

202245
[issues]: https://github.com/googlemaps/google-maps-services-js/issues
203246
[contrib]: https://github.com/googlemaps/google-maps-services-js/blob/master/CONTRIBUTING.md

e2e/routes.test.ts

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Copyright 2020 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
import { decodePath } from "../src/util";
18+
import { routes } from "../src/routes";
19+
import {
20+
RouteTravelMode,
21+
RouteUnits,
22+
RoutingPreference,
23+
} from "../src/interfaces/routes";
24+
25+
test("routes should get correct result", async () => {
26+
const params = {
27+
origin: {
28+
location: {
29+
latLng: { latitude: 37.419734, longitude: -122.0827784 }, // Origin coordinates
30+
},
31+
},
32+
destination: {
33+
location: {
34+
latLng: { latitude: 37.41767, longitude: -122.079595 }, // Destination coordinates
35+
},
36+
},
37+
travelMode: RouteTravelMode.DRIVE,
38+
routingPreference: RoutingPreference.TRAFFIC_AWARE,
39+
computeAlternativeRoutes: false,
40+
routeModifiers: {
41+
avoidTolls: false,
42+
avoidHighways: false,
43+
avoidFerries: false,
44+
},
45+
languageCode: "en-US",
46+
units: RouteUnits.IMPERIAL,
47+
apiKey: { key: process.env.GOOGLE_MAPS_API_KEY },
48+
};
49+
50+
const r = await routes({
51+
params: params,
52+
apiKey: { key: process.env.GOOGLE_MAPS_API_KEY },
53+
});
54+
55+
expect(r.config.url).toContain(
56+
"routes.googleapis.com/directions/v2:computeRoutes"
57+
);
58+
59+
expect(r.data.routes[0].legs[0].distanceMeters).toBeGreaterThan(0);
60+
expect(
61+
decodePath(r.data.routes[0].polyline.encodedPolyline)[0].lat
62+
).toBeDefined();
63+
});

src/client.test.ts

+8
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
TextSearchRequest,
3535
NearestRoadsRequest,
3636
SnapToRoadsRequest,
37+
RoutesRequest, // Import RoutesRequest
3738
X_GOOG_MAPS_EXPERIENCE_ID,
3839
defaultAxiosInstance,
3940
} from "./client";
@@ -261,4 +262,11 @@ describe("client wraps all functions correctly", () => {
261262
client.snapToRoads({} as SnapToRoadsRequest);
262263
expect(mock).toBeCalledWith({}, client["axiosInstance"]);
263264
});
265+
266+
test("client wraps routes correctly", () => {
267+
const routes = require("./routes");
268+
const mock = (routes.routes = jest.fn());
269+
client.routes({} as RoutesRequest);
270+
expect(mock).toBeCalledWith({}, client["axiosInstance"]);
271+
});
264272
});

src/client.ts

+14-20
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,9 @@ import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
8585
import { HttpsAgent } from "agentkeepalive";
8686
import { customAdapter } from "./adapter";
8787

88-
// Cannot be `import` as it's not under TS root dir
88+
// Import Routes API
89+
import { RoutesRequest, RoutesResponse, routes } from "./routes";
90+
8991
export const version = require("../package.json").version;
9092
export const defaultHttpsAgent = new HttpsAgent({ keepAlive: true });
9193
export const defaultTimeout = 10000;
@@ -117,6 +119,7 @@ export interface ClientOptions {
117119
config?: Config;
118120
experienceId?: string[];
119121
}
122+
120123
/**
121124
* Client is a light wrapper around API methods providing shared configuration for Axios
122125
* settings such as retry logic using the default retry-axios settings and gzip encoding.
@@ -198,28 +201,11 @@ export class Client {
198201
timezone(request: TimeZoneRequest): Promise<TimeZoneResponse> {
199202
return timezone(request, this.axiosInstance);
200203
}
204+
201205
geolocate(request: GeolocateRequest): Promise<GeolocateResponse> {
202206
return geolocate(request, this.axiosInstance);
203207
}
204-
/**
205-
* An example use of this function.
206-
*
207-
* ```javascript
208-
* import { Client } from '@googlemaps/google-maps-services-js';
209-
*
210-
* const args = {
211-
* params: {
212-
* key: '<your-api-key>',
213-
* address: 'Perth 4WD & Commercial Centre',
214-
* }
215-
* };
216-
* const client = new Client();
217-
* client.geocode(args).then(gcResponse => {
218-
* const str = JSON.stringify(gcResponse.data.results[0]);
219-
* console.log(`First result is: ${str}`);
220-
* });
221-
* ```
222-
*/
208+
223209
geocode(request: GeocodeRequest): Promise<GeocodeResponse> {
224210
return geocode(request, this.axiosInstance);
225211
}
@@ -263,12 +249,18 @@ export class Client {
263249
textSearch(request: TextSearchRequest): Promise<TextSearchResponse> {
264250
return textSearch(request, this.axiosInstance);
265251
}
252+
266253
nearestRoads(request: NearestRoadsRequest): Promise<NearestRoadsResponse> {
267254
return nearestRoads(request, this.axiosInstance);
268255
}
256+
269257
snapToRoads(request: SnapToRoadsRequest): Promise<SnapToRoadsResponse> {
270258
return snapToRoads(request, this.axiosInstance);
271259
}
260+
261+
routes(request: RoutesRequest): Promise<RoutesResponse> {
262+
return routes(request, this.axiosInstance);
263+
}
272264
}
273265

274266
export {
@@ -304,4 +296,6 @@ export {
304296
TextSearchResponse,
305297
TimeZoneRequest,
306298
TimeZoneResponse,
299+
RoutesRequest,
300+
RoutesResponse,
307301
};

src/common.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1632,7 +1632,7 @@ export interface SnappedPoint {
16321632
* Represents a descriptor of an address.
16331633
*
16341634
* <p>Please see <a
1635-
* href="https://mapsplatform.google.com/demos/address-descriptors/">Address
1635+
* href="https://mapsplatform.google.com/demos/address-descriptors/">Address
16361636
* Descriptors</a> for more detail.
16371637
*/
16381638
export interface AddressDescriptor {
@@ -1706,7 +1706,7 @@ interface Area {
17061706
containment: Containment;
17071707
}
17081708

1709-
/**
1709+
/**
17101710
* An enum representing the relationship in space between the area and the target.
17111711
*/
17121712
enum Containment {
@@ -1733,4 +1733,4 @@ interface LocalizedText {
17331733
// For more information, see
17341734
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
17351735
languageCode: string;
1736-
}
1736+
}

0 commit comments

Comments
 (0)