diff --git a/examples/Google Directions.md b/examples/Google Directions.md new file mode 100644 index 0000000..d55e341 --- /dev/null +++ b/examples/Google Directions.md @@ -0,0 +1,37 @@ +# Google Directions With Server-side JavaScript + +Returns directions between two points from Google Maps. [Outscraper API](https://app.outscraper.cloud/api-docs#tag/Google/paths/~1maps~1directions/get). + +## Installation + +Install the package with: +```bash +npm install outscraper --save +# Or +yarn add outscraper +``` + +[Link to the NPM package page](https://www.npmjs.com/package/outscraper) + +## Initialization +```js +const Outscraper = require('outscraper'); +// Or using ES modules: +import Outscraper from 'outscraper'; + +let client = new Outscraper('SECRET_API_KEY'); + +``` +[Link to the profile page to create the API key](https://app.outscraper.com/profile) + +## Usage + +```js +// Returns directions: +client.googleMapsDirections([ + ['29.696596, 76.994928', '30.715966244353, 76.8053887016268'], + ['29.696596, 76.994928', '30.723065, 76.770169'] +]).then(response => { + console.log(response); +});; +``` \ No newline at end of file diff --git a/index.js b/index.js index 90617e2..bf72718 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,6 @@ const https = require('https'); const querystring = require('querystring'); -const { toArray, removeEmpty } = require('./utils'); +const { toArray, removeEmpty, formatQueries } = require('./utils'); class Outscraper { constructor(apiKey) { @@ -122,10 +122,9 @@ class Outscraper { return this.handleAsyncResponse(response, asyncRequest); } - async googleMapsDirections(origin = '', destination = '', departureTime = null, finishTime = null, interval = null, travelMode = 'best', language = 'en', region = null, fields = null, asyncRequest = true) { + async googleMapsDirections(query, departureTime = null, finishTime = null, interval = null, travelMode = 'best', language = 'en', region = null, fields = null, asyncRequest = true) { const response = await this.getAPIRequest('/maps/directions', { - origin: toArray(origin), - destination: toArray(destination), + query: query ? formatQueries(query) : null, departure_time: departureTime, finish_time: finishTime, interval: interval, diff --git a/utils.js b/utils.js index 1fdbba0..b549675 100644 --- a/utils.js +++ b/utils.js @@ -1,3 +1,5 @@ +const QUERY_DELIMITER = ' '; + exports.toArray = (value) => { if (Array.isArray(value)) { return value; @@ -9,3 +11,13 @@ exports.toArray = (value) => { exports.removeEmpty = (obj) => { return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); } + +exports.formatQueries = (q) => { + if (Array.isArray(q)) { + if (q.every(i => Array.isArray(i))) { + return q.map(pair => pair.join(QUERY_DELIMITER)); + } + return q; + } + return [q]; +}