等待Loop完成,然后再将值传递到javascript(还包括Google Maps)中。 [英] Wait for Loop to finish before passing the value in javascript (also google maps).

查看:83
本文介绍了等待Loop完成,然后再将值传递到javascript(还包括Google Maps)中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太使用JavaScript,因此对回调和响应不太熟悉。我正在使用谷歌地图来绘制出点A和点X,Y,Z之间的距离。问题是,我想使用JavaScript来确定X,Y,Z中哪个点最接近A,并且它们映射出它们之间的方向。

I don't use javascript much so I am not that familiar with callbacks and responses. I am using google maps to map out distance between point A and point X,Y,Z. The catch is, I want to use javascript to determine which of the points X,Y,Z is closest to A and them map out the directions between them.

我的代码工作中。我可以找出所有3个目的地中最短的距离,但是我对这种愚蠢的外观感到困惑。

My code is working. I can figure out the shortest distance out all the 3 destinations but I am stuck with this stupid for look.

您会看到,Google使用异步回调向浏览器提供数据如果我运行一个for循环以1对1的方式检查所有3个目的地,则会得到错误的结果。

You see, Google uses async callbacks to provide data to the browser and if I run a for loop to check all the 3 destinations 1 by 1, I get incorrect results.

这是代码:

var maxDistance = 99999999999;
var destn;
for (var i = 0; i < locations.length; i++) {
  var thisDistance = 0;
  var start = origin;
  var end = locations[i];
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      thisDistance = response.routes[0].legs[0].distance.value;
      if (thisDistance < maxDistance) {
        destn = response.routes[0].legs[0].end_address;
        maxDistance = thisDistance;
      }
    } else {
      document.getElementById("addressNotFound").style.display = 'block';
    }
  });
}
calcShortestRoute(origin, destn);

显然,当我调用此函数时,由于循环结束,destn的值变为未定义Google处理程序尚未收到数据。如果我再调用该函数1次,则会得到从上一个回调收到的destn值(此回调之前未定义)。

So obviously when I call this function, the value of destn comes up as undefined since the loop finishes and the google handler hasnt received the data yet. If I call the function 1 more time, I get the destn value that was received from the previous callback (which gave undefined before).

请告诉我如何解决此问题。

Someone please tell me how I can fix this.

推荐答案

您需要等待,直到所有三个Google响应都已返回。一个简单的解决方案是:将距离计算函数调用最后移到匿名函数中,然后仅在所有响应都返回后才计算距离:

You need to wait until all three Google responses have been returned. A simple solution is: move you distance calculation function call into the anonymous function at the end, and then calc the distances only if all responses have returned:

        // global count variable
        var callbackCount = 0;

        for (var i = 0; i<locations.length; i++) {
            var thisDistance=0;
            var start = origin;
            var end = locations[i];
            var request = {
                origin:start,
                destination:end,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    thisDistance = response.routes[0].legs[0].distance.value;
                    if (thisDistance < maxDistance) {
                        destn = response.routes[0].legs[0].end_address;
                        maxDistance = thisDistance;
                    }                            
                }
                else {
                    document.getElementById("addressNotFound").style.display = 'block';
                }

                // move this to here, and pass in number of locations
                calcShortestRoute(origin, destn, locations.length);
            });



        }

然后calcShortestRoute看起来像:

then calcShortestRoute looks like:

function calcShortestRoute(origin, destn, locationCount) {

  // increment callback count
  callbackCount++;

  if (callbackCount == locationCount) {   // all responses have returned


     // do your distance checking      
     ....

   }
}

这篇关于等待Loop完成,然后再将值传递到javascript(还包括Google Maps)中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆