Why doesn’t my . map run?

Asked

Viewed 74 times

1

I have the following function:

function (markers) {
  const geocoder = new google.maps.Geocoder()
  const geocodingResults = []
  markers.forEach((latLong) => {
    geocoder.geocode({ 'location': latLong }, (result, status) => {
      // console.log(results, status)
      if (status !== 'OK') { return false }
      geocodingResults.push(result)
    })
  })
  console.log('geocodingResults', geocodingResults)
  return geocodingResults.map((address) => {
    console.log('address', address)
    return address[0].address_components[1].short_name
  })
}

In the console I receive geocoding Results being an array of size 2 but never get the log "address", what can this happen ? my map is not running ?

  • What result of console.log('geocodingResults', geocodingResults) ?

  • https://pastebin.com/eXtvspBq

  • Have you tried removing the Return before the map? Instead of Return put a variable, and off a console map in the variable.

  • You can add the result of console.log(JSON.stringify(geocodingResults)) to make it easier to view?

1 answer

1


That method geocoder.geocode is asynchronous. That means the line geocodingResults.push(result) will be run after yours .map. It’s the same situation as this other question.

For the map to have the value you want you have to run the rest of the code inside the callback geocoder.geocode.

An example would be like this:

function getShortNames(markers) {
  const geocoder = new google.maps.Geocoder();

  // tens de criar uma promise para cada chamada assíncrona
  const promises = markers.map(latLong => {
    return new Promise((resolve, reject) => {
      geocoder.geocode({
        'location': latLong
      }, (result, status) => {
        // console.log(results, status)
        if (status !== 'OK') reject();
        else resolve(result);
      })
    });

    // Aqui tens de esperar que todas as callbacks sejam chamadas e depois podes dar um return
    return Promise.all(promises) then((geocodingResults) => {
      return geocodingResults.map((address) => {
        console.log('address', address)
        return address[0].address_components[1].short_name
      })
    }).catch(err => console.log(err));
  });
}

getShortNames([/*markers*/]).then(names => console.log(names);

insert link description here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.