0

I am following up to this question, where there is an asynchronous request to draw a route from point A to B, called setDirections. In the end, we want an endpoint to be at the center, but by default the map centers to show most of the route. Simply adding setCenter(endpoint) after setDirections does not result in centering at the endpoint.

I reasoned by using a setTimeout, that setDirections seems to be another asynchronous function, because after waiting a bit, the map centers as I wish.

So how can I ensure my setCenter runs only after setDirections is done? I thought about callbacks but it is not doing what I want.

In my code I did the following, using patterns from Recurial and JavaScript Callback after calling function:

  1. wrap the existing directions drawing code with function wrapper (callback) {
  2. the directions request and drawing is asynchronous, so inside the successful response block, I call callback(this.marker.getPosition())
  3. after defining the wrapper, I call wrapper(function(latLng) { map.setCenter(latLng) })

Here's a JSFiddle. http://jsfiddle.net/EeXQF/2/

The setTimeout "solution" is there, just needs to be uncommented.

Community
  • 1
  • 1
Heitor Chang
  • 6,038
  • 2
  • 45
  • 65

1 Answers1

1

(to be honest I dont really follow what you asking, I guess there is a lot of background to your question, which I just dont have. )

But, one thing to note, Javascript is generally single threaded. Only one bit of code is getting executed at once.

So your code asks for something to happen. But it can't generally happen, while your code is still running. The browser will execute it when your code has finished. Actions you 'start' will get added to a queue, and run later.

setTimeout, adds the callback onto the end of the queue. So main function will finish. maps will get a chance to do its stuff (it has stuff in the queue), then your callback will fire.

(its more complicated than that in reality, but might help explain what you seeing)

barryhunter
  • 20,886
  • 3
  • 30
  • 43
  • Yeah, I should really go back and rewrite it. Thanks for pointing that out. The whole first half is irrelevant. – Heitor Chang Apr 18 '12 at 17:30
  • But its also more fundermental than that. You dont really have a 'question'. Also saying *what* you want to happen, and what actully happens instead would be useful. – barryhunter Apr 18 '12 at 17:32