当我使用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!!
你确定你的'DirectionService.route'正在同步执行(在你的最后一行'console.log(x)'之前)吗?我在上面的代码中没有看到实际运行'DirectionService.route'函数的任何内容。 – brianvaughn 2015-04-05 23:00:51
回调函数在console.log()调用底部之后运行。 DirectionService.route()执行异步操作,因此不能保证何时调用回调函数。无论DirectionService.route()是否已完成运行,代码执行都将继续。 – brianjob 2015-04-05 23:04:33
可能的重复[为什么我的变量在函数内部修改后没有改变? - 异步代码引用](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