-1

When i use DirectionService to place coordinates into a polyline... i realize, that variable polyline outside the callback function wasn't changed at all.. and i also tried it for variable x.. and it was the same.. i just want this code to works.. is there anyway to make variable outside callback changed when it changed on callback scope ?

var polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#FF0000',
    strokeWeight: 3});

    var x = 0;
    DirectionService.route(request, function(result, status) {
        x = 1;
        if (status == google.maps.DirectionsStatus.OK)
        {
            var legs = result.routes[0].legs;       
            for ( i = 0; i < legs.length; i++) {
                var steps = legs[i].steps;
                for ( j = 0; j < steps.length; j++) {
                    var nextSegment = steps[j].path;
                    for ( k = 0; k < nextSegment.length; k++) {
                        polyline.getPath().push(nextSegment[k]);]
                    }
                }
            }
        console.log(polyline.getPath().getArray().length); // not zero
        console.log(x) // x = 1;
    }
});

map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
console.log(polyline.getPath().getArray().length); // the array length is 0
console.log(x) // x remains ZERO!!
  • Are you sure your `DirectionService.route` is executing synchronously (before your last line `console.log(x)`) ? I don't see anything in your code above that's actually running the `DirectionService.route` function. – bvaughn Apr 05 '15 at 23:00
  • 1
    The callback function is being run after the console.log() calls at the bottom. DirectionService.route() performs an asynchronous operation so there are no guarantees about when the callback function is called. Code execution will continue regardless of whether DirectionService.route() has finished running or not. – brianjob Apr 05 '15 at 23:04
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – geocodezip Apr 05 '15 at 23:26

1 Answers1

0

console.log(x) (at the end) fires before callback function is executed. Keep concurrency in mind.

Tin Rabzelj
  • 132
  • 2
  • 8
  • 1
    JavaScript is single threaded so it isn't a concurrency issue, but rather an execution order issue. – brianjob Apr 05 '15 at 23:06
  • but, is there a way to fix it ? like waiting until this direction service callback is called ? – Tegar Percy Apr 05 '15 at 23:19
  • Do what you can with the result in the callback. You could call another function in the callback, which continues with stuff dependent on result. – Tin Rabzelj Apr 05 '15 at 23:33