0

I have Google Maps API Key and want to use it with google-distance-matrix library. But i don't know where to put my Key and integrate it with above stated library here is my code

const distanceAPI = require('google-distance-matrix')

dispatchers.dispatchers.map( (dispatcher) => {
distanceAPI.matrix(dispatcher.location.coordinates, call.pickupLocationCoordinates.coordinates, mode, function(err, distances) {
    
    console.log("distances")
    console.log(distances)
})

})

Following error is still being thrown

error = 'You must use an API key to authenticate each request to Google Maps Platform APIs.'

I have also create a variable in .env file with following

G_API = key

Kindly let me know the right way of using the map service.

Jamshaid Sabir
  • 73
  • 2
  • 10

1 Answers1

0

As mentioned in the README.md of google-distance-matrix you have to precise your key in distance.key() method.

distance.key('myAPIkey');

If your using a .env file you should call your env variable variable with process.env and dotenv package.

index.js :

require('dotenv').config();

const distance = require('google-distance-matrix');

distance.key(process.env.MY_API_KEY);

// Working example code
var origins = ['San Francisco CA'];
var destinations = ['New York NY', '41.8337329,-87.7321554'];

distance.matrix(origins, destinations, function (err, distances) {
    if (!err)
        console.log(distances);
})

.env :

MY_API_KEY=1234AEB

You can check a full working example on the google-distance-matrix doc here

Thibault Walterspieler
  • 2,272
  • 2
  • 15
  • 25