0

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.

Dominik
  • 6,078
  • 8
  • 37
  • 61
  • The DistanceMatrixService is asynchronous. You can't return anything from its callback function. You need to use the data in the callback function, when/where it is available, or you could try using a promise. – geocodezip Dec 27 '20 at 22:29
  • You're absolutely right! I wasn't able to get the values from the promise but I've managed to handle it in the callback, thank you :) – Oli Kritzler Dec 28 '20 at 15:38

0 Answers0