I am trying to get distances between two addresses using Nodejs and the distancematrix API from google maps. I realize that I need to wait for the API to complete 'getting' the distance before I can actually use it, but I am having trouble figuring out how to do this. I have already looked at other examples online but can't seem to get the correct return value.
const origins = [{lat:33.1581549623887,lng: -96.58113451598159}]
const destinations = ["9200 World Cup Way, Frisco, TX 75033"]
function getDistances(origins, destinations){
client.distancematrix({
params:{
origins:origins,
destinations:destinations,
key:"some-key",
units:"imperial"
}
})
.then((r) => {
if(r.data.rows[0].elements != undefined){
// console.log(r.data.rows[0].elements)
return(r.data.rows[0].elements);
}
})
.catch((e) =>{
console.log(e.response.data.error_message);
})
}
async function getClosestField(employee, games){
closestField = games[0]
let distance = await getDistances(origins,destinations)
console.log(distance) //ALWAYS UNDEFINED
return(distance)
}
getClosestField(employees[0],games)
Note: I have the appropriate key and it's not actually "some-key"
The result of console.log(distance)
is undefined..
How can I properly wait for getDistances()
to complete before I console log it?
Since the client returns a promise, I thought the .then
portion would only execute after completion.