Problem:
I've tried as many ways as I know how and I'm still struggling to return values from googles DistanceMatrixService
.
What I am trying to do is create a function that takes in an object:
{
id: id,
currentLat: lat,
currentLng: lng,
newLat: locationLat,
newLng: locationLng,
travelMode: travelMode
}
and returns a new object:
{
id:id,
distance: x,
timeTaken: x
}
Using the DistanceMatrixService
If I assign a variable to this function:
function getDurationObject(travelObj){
let duration
const origin1 = {lat,lng}
const destination1 = {lat: travelObj.newLat, lng: travelObj.newLng}
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1],
destinations: [destination1],
travelMode: travelObj.travelMode,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false,
},callback)
function callback(response, status) {
if (status == 'OK') {
var results = response.rows[0].elements
var element = results[0]
duration = element.duration.text
}
return duration
}
}
It returns undefined
.
And if I try this function:
function getDurationObject(travelObj){
const getDistanceMatrix = (service, travelObj) => new Promise((resolve, reject) => {
service.getDistanceMatrix(travelObj, (response, status) => {
if(status === 'OK') {
resolve(response)
} else {
reject(response);
}
})
})
let getDistance = async () => {
const origin = {lat,lng}
const final = {lat: travelObj.newLat, lng: travelObj.newLng}
const service = new google.maps.DistanceMatrixService();
const result = await getDistanceMatrix(
service,
{
origins: [origin],
destinations: [final],
travelMode: travelObj.travelMode
}
)
const results = result.rows[0].elements
let response =
{distance:results[0].distance.text,
timeTaken:results[0].duration.text,
id:travelObj.id}
return response
}
return getDistance()
}
}
It returns a promise as expected however I can't seem to return the values from the promise however I try. It's possible that I just don't know how to assign a variable properly to the values of the promise.