I am trying to connect to the Google Directions API with my node server via a callback function but for some reason I cannot get a response from the Google API. Funny enough I had this working a few days ago and somehow I managed to break it. My controller contains the following code - calling a function within google_api.js:
var google = require('../scripts/google_api')
var inputs = {
origin: "1600 Amphitheatre Parkway, Mountain View, CA",
destination: "1 Infinite Loop, Cupertino, CA 95014, USA",
mode: "driving",
};
function getDirections(data, callback){
console.log("First");
callback(data);
console.log("Second");
};
getDirections(inputs, google.directions);
My google_api.js file contains the following code (with a valid API key):
var googleMapsClient = require('@google/maps').createClient({
key: 'XXX'
});
module.exports.directions = (req, res) => {
console.log(req);
googleMapsClient.directions({
origin: req.origin,
destination: req.destination,
mode: req.mode,
}, function(err, response) {
if (!err) {
console.log(response.json.results);
};
});
};
console.log("First"), console.log("Second") and console.log(req) all behave as expected so the problem must exist inside the googleMapsClient.directions() function. The API key is tested and works with another front-end JS function so it isn't a problem with the key. I managed to get the function to output an error once with a EHOSTUNREACH error but replicating this has not been consistent. I fear I am missing something so basic that I don't even know where to begin. Any help would be great! Thanks