简体   繁体   中英

How to run a function only after directionsDisplay ends?

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.

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM