Use Google directionService result in parent function context =s


#1

Hello everybody !

I encounter difficulties for use the result of request from directionService.

i will try to explain :

i have function which need return a “trip”. For build this “trip” i need to use the params of “createTrip” function and the result of directionService.rout() from google map direction service API (https://developers.google.com/maps/documentation/javascript/directions?hl=en)

createTrip(someParams)  {
    var trip = {};

   directionsService.route(
			options, 
			function(result, status: any) {
				console.log('this', this);
				if (status === 'OK') {
					console.log('result', result);
					// directionsDisplay.setDirections(result);
				}
			}
		);

  trip['attr1'] = someParams[...]
  trip['attr2'] = someParams[...]
  trip['attr3'] = [ **HERE I NEED USE PROPERTY OF THE RESULT FROM DIRECTIONSERVICE**]

  return trip;
}

i think i need to wait asynchronous the result of the request for build my trip object, but i failed…

Someone have any idea ?? Thanks =)


#2
  • never type the word “function” inside the body of one.
  • you are not going to be able to return trip out of here no matter what you do.
  • always use let instead of var.
  • declare types for all parameters and return values

It is probably going to be simplest to focus on just the call to route:

mapRoute(): Promise<DirectionsResult> {
  return new Promise((resolve, reject) => {
    directionsService.route(options, (dr, status) => {
      if (status === 'OK') {
        resolve(dr);
      } else {
        reject(status);
      }
    });
  });
}

Once this has been Promisified, you can build your trip like so:

return this.mapRoute().then((route) => {
  let trip = {};
  trip.attr1 = whatever;
  trip.attr3 = route;
  return trip;
} 

The ultimate consumer of the trip must be able to receive a Promise and only in a then clause can the actual trip be relied on.


#3

Thank you very much for the help and advice rapropos