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:
- wrap the existing directions drawing code with
function wrapper (callback) { - the directions request and drawing is asynchronous, so inside the successful response block, I call
callback(this.marker.getPosition()) - after defining the
wrapper, I callwrapper(function(latLng) { map.setCenter(latLng) })
Here's a JSFiddle. http://jsfiddle.net/EeXQF/2/
The setTimeout "solution" is there, just needs to be uncommented.