2015-04-05 77 views
-1

当我使用DirectionService将坐标放置到多段线中时... 我意识到,回调函数外部的变量多段线根本没有改变.. 我也试过了它的变量x ..和它是一样的.. 我只是想让这段代码工作.. 是否有变更外部回调改变时,它改变了回调范围?执行回调函数之前回调中的变量不能改变

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!! 
+0

你确定你的'DirectionService.route'正在同步执行(在你的最后一行'console.log(x)'之前)吗?我在上面的代码中没有看到实际运行'DirectionService.route'函数的任何内容。 – brianvaughn 2015-04-05 23:00:51

+1

回调函数在console.log()调用底部之后运行。 DirectionService.route()执行异步操作,因此不能保证何时调用回调函数。无论DirectionService.route()是否已完成运行,代码执行都将继续。 – brianjob 2015-04-05 23:04:33

+0

可能的重复[为什么我的变量在函数内部修改后没有改变? - 异步代码引用](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – geocodezip 2015-04-05 23:26:10

回答

0

的console.log(x)的(末尾)触发。记住并发。

+1

JavaScript is single因此它不是一个并发问题,而是一个执行顺序问题。 – brianjob 2015-04-05 23:06:54

+0

谢谢..我现在明白了.. – 2015-04-05 23:18:29

+0

但是,有没有办法解决它?像等到这个方向服务回调被称为? – 2015-04-05 23:19:52