Google Distance Matrix API for Node.js
Easily get traveling distance and duration data between locations with the Google Distance Matrix API
Installation
npm install google-distance
Usage
var distance = ; distance;
The above example outputs the following data
object:
index: null distance: '807 km' distanceValue: 807366 duration: '7 hours 30 mins' durationValue: 26981 origin: 'San Francisco, CA, USA' destination: 'San Diego, CA, USA' mode: 'driving' units: 'metric' language: 'en' avoid: null sensor: false
Batch Mode
This example will return an array of data
objects corresponding to all origin/destination pairs.
distance;
Result:
Origin | Destination |
---|---|
San Francisco, CA | San Diego, CA |
San Francisco, CA | Seattle, WA |
San Diego, CA | San Diego, CA |
San Diego, CA | Seattle, WA |
Additional Parameters
Here is a full list of options you can include to tailor your query:
- origin, destination -
name
(eg.'San Francisco, CA'
) |latitude/longitude
(eg.'51.510652,-0.095444'
) - index -
null
(default) | specify an index for identification - mode -
'driving'
(default) |'walking'
|'bicycling'
- units -
'metric'
(default) kilometers/meters |'imperial'
miles/feet - language -
'en'
(default) | more languages - avoid -
null
(default) |'highways'
|'tolls'
- sensor -
false
(default) |true
| determines if GPS is used to find user location
Note: The units
setting only affects the text displayed within distance
fields.
distanceValue
is always in meters, and durationValue
is always in seconds.
More Examples
This example specifies mode
and units
:
distance;
Outputs:
index: null distance: '499 mi' distanceValue: 802534 duration: '1 day 21 hours' durationValue: 161896 origin: 'San Francisco, CA, USA' destination: 'Los Angeles, CA, USA' mode: 'bicycling' units: 'imperial' language: 'en' avoid: null sensor: false
Let's use latitude and longitude for our origin/destination and an index:
distance;
Outputs:
index: 1 distance: '21.9 km' distanceValue: 21946 duration: '21 mins' durationValue: 1251 origin: 'Octavia Boulevard, San Francisco, CA 94102, USA' destination: '2066-2070 University Avenue, Berkeley, CA 94704, USA' mode: 'driving' units: 'metric' language: 'en' avoid: null sensor: false
API Keys
Using an API key is not required, but recommended since you can track your usage and make sure you don't exceed Google's quota. You can request a key by following these steps.
Specify an API key for use like this:
var distance = ;distanceapiKey = 'API_KEY';
Business users can omit the API key and instead specify their business client and signature keys:
var distance = ;distancebusinessClientKey = 'CLIENT_KEY';distancebusinessSignatureKey = 'SIGNATURE_KEY';
Running Tests
-
Install the development dependencies:
npm install
-
Run the tests:
npm test