等待循环完成,然后传递javascript中的值(也是google地图)。 [英] Wait for Loop to finish before passing the value in javascript (also google maps).

查看:156
本文介绍了等待循环完成,然后传递javascript中的值(也是google地图)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不使用javascript太多,所以我不熟悉回调和响应。我使用google地图绘制点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.

我的代码工作中。

你看,Google使用异步回调来向浏览器提供数据如果我运行一个for循环检查所有3个目的地1 1,我得到不正确的结果。

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处理程序hasnt还没有收到数据。如果我再一次调用函数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).

有人请告诉我,

推荐答案

您需要等待所有三个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);
            });



        }

then 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      
     ....

   }
}

这篇关于等待循环完成,然后传递javascript中的值(也是google地图)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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