1

I am using google map v3 to do some address translation. I pass the request and callback function to Geocoder.geocode. The callback function will add a marker on the map. After all, I use map.FitBounds(fullBounds) to make all makers in sight, where map being the Map obejct, fullBounds being LatLngBounds obejct.

below is piece of my code:

    for(i = 0; i < requestArray.length; i ++)
    {
        geo.geocode(requestArray[i], calbck);
    }

My problem is that when I invoke map.fitBounds(fullBounds) in calbck, not all callback functions have finished(always none in my observation). So how can I delay the fitBounds so that all callback functions have finished?

onemach
  • 4,265
  • 6
  • 34
  • 52

2 Answers2

1

If you know the number of callbacks you can call some other function in your callback in which you increase the counter, and when the counter is the same as number of callbacks you execute the code.

Something like:

function myFunctionToExecuteAfterCallbacks()
{
  numCallbacks++;
  if(numCallbacks == numAllCallbacks)
  {
    // Code to execute here...
  }
}

At least that's how I solved it one time. Don't know any better solutions. Maybe instead of calling another function you could fire an event. But it's almost the same...

Btw, I found some topics on this:

Best solution to wait for all ajax callbacks to be executed

javascript: execute a bunch of asynchronous method with one callback

Community
  • 1
  • 1
Matjaz Muhic
  • 5,328
  • 2
  • 16
  • 34
0

If you use promises, take a look at Promise.all().

You can also do a recursive callback.

doStuff() {
  if (requestArray.length) {
    geo.geocode(requestArray.pop(), this.doStuff)
  } else {
    // we're done;
  }
}
Mariano LEANCE
  • 1,036
  • 13
  • 10