0

from within a Google API maps places call, I also need to retreive place coords:

if (status != google.maps.places.PlacesServiceStatus.OK) {
  callback(data);
} else {
  var geocoder = new google.maps.Geocoder();
}
for (var i = 0; i < predictions.length; i++) {
  let coords = geocoder.geocode({
    'placeId': predictions[i].place_id,
  },
  function (responses, status) {
    if (status == 'OK') {
      var lat = responses[0].geometry.location.lat()
      var lng = responses[0].geometry.location.lng()
      return (lat + '#' + lng)
      //CONSOLE LOG HERE IS WORKING the RETURN NOT
    }
  });

  console.log(coords);
  data.results.push({
    id: predictions[i].place_id,
    text: predictions[i].description,
    value: coords,
  });
}

unluckily I get "PROMISE" value, rather than coords string one. I can't get the way to return and unwrap the promise :(

can you help me?

tyvm

Guerric P
  • 30,447
  • 6
  • 48
  • 86
lyllo
  • 45
  • 7

1 Answers1

0

Your code is asynchronous and there is no possible way of making it synchronous, so instead of trying to return something else than a Promise, just adapt your code:

if (status != google.maps.places.PlacesServiceStatus.OK) {
  callback(data);
} else {
  var geocoder = new google.maps.Geocoder();
}

const coords = await Promise.all(
    predictions.map(x => geocoder.geocode({
        'placeId': x.place_id
      })).map(x => x.then(responses => {
        const lat = responses[0].geometry.location.lat()
        const lng = responses[0].geometry.location.lng()
        return (lat + '#' + lng)
      })).map(x => x.then(coords => ({
        value: coords
      }))));

data.results = predictions.map(({ place_id, description }) => ({ place_id, description })).map((x, i) => ({ ...x, ...coords[i] }));

console.log(data.results);

Disclaimer: I didn't test it so it may contain mistakes

Note: this code implies that the surrounding function is declared as async which means it also returns a Promise so you have to adapt the rest of your code as well.

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • ty, I was trying to edit the original one taken from here: https://jsfiddle.net/angelmarde/perqpp9f/2/ – lyllo May 10 '21 at 20:02