同步调用for循环中的jQuery函数

时间:2017-11-02 04:45:31

标签: javascript jquery synchronous

我正在开展Google地图的网页工作。我想调用一个jQuery函数来启动地图上的路由。我正在使用JSON填充数组。我想在循环中调用 startRoute 函数,但在完成之后(在 startRoute 之后完成而不是循环)。

这个 startRoute 函数提供了新的lat,long set,我必须沿着路径(例如实时跟踪)将动画从最后一个位置移动到新的当前位置而不刷新地图,TIA。

HtmlProvider

1 个答案:

答案 0 :(得分:-1)

您可以像这样修改循环:

var mapIsMoving = false;
var CurrentLatLong = [];                                

google.maps.event.addListener(map, "idle", function() {
    mapIsMoving = false;
});

for(var i = 0 ; i < RoutePointsLength; i++){
    if(mapIsMoving){
       i--;
       continue;
    }
    CurrentLatLong.push([data._DriverLocation[i].Latitude, data._DriverLocation[i].Longitude]); 
    localStorage["EndLatLong"] = null;
    localStorage["EndLatLong"] = JSON.stringify(CurrentLatLong[0]).replace('[', '').replace(']', '');          
    // run the route     
    startRoute();      
}

和startRoute方法:

function startRoute() {
    mapIsMoving = true;
    polyline = null;
    poly2 = null;
...
...
...

因为setTimeout会使方法在另一个线程中运行,因此循环无法检测到它的完成。您需要在同一个线程上运行它来阻止循环执行下一个路由绘图。