Google Maps Directions Service,如何等待所有请求完成?

时间:2020-04-10 17:39:27

标签: javascript google-maps-react

我有一个技术人员列表,我需要获取特定位置之间的单个行驶时间。我一直在使用脚本在Google Sheets中执行此操作,但是我宁愿在Web应用程序中执行计算。当然这里有一些问题。一个是我不能在没有某种延迟的情况下仅在for循环中发出这些请求,否则我将得到一个over_query_limit错误。另一个问题是,我想要一种让用户知道所有请求均已完成的方法,而这正是我所坚持的部分。我目前正在使用google-maps-react npm软件包来完成此操作。

这是我目前拥有的:

TechDriveTimeTest(techs, kioskInfo){
        let result = []
        techs.forEach(tech => {
            if(tech.Address != "" && !tech.Notes.includes('Not')){
                result.push(tech);
            }
        })

        //console.log(result);

        let directionsService = new google.maps.DirectionsService();

        result.forEach((tech, index) => {
            let techAddress = tech.Address + " " + tech.City + " " + tech.State + " " + tech.Zip

            let req = {
                origin: techAddress,
                destination: 'some destination',
                travelMode: 'DRIVING'
            }

            this.GetTime(index, req, directionsService);

        })
    }

    GetTime(i, req, service){
        setTimeout(function(){
            service.route(req, function(res, status){
                if(status == 'OK'){
                   let time = res.routes[0].legs[0].duration.text
                   console.log(time);
                }
            })
        }, (i+1) * 1000)
    }

此代码可以很好地延迟请求,这样我就不会再收到错误了,但是很高兴知道所有请求何时完成,以便我可以通知用户。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用递归一次运行一个请求,这是一个示例:

function TechDriveTimeTest(techs, kioskInfo){
    techs = techs.filter(tech => tech.Address != "" && !tech.Notes.includes('Not'))
                 .map(tech => `${tech.Address} ${tech.City} ${tech.State} ${tech.Zip}`);

    const directionsService = new google.maps.DirectionsService();
    recursion();
    function recursion() {
        const techAddress = techs.shift();
        directionsService.route({
            origin: techAddress,
            destination: 'some destination',
            travelMode: 'DRIVING'
        }, function(res, status){
            if(status == 'OK'){
               let time = res.routes[0].legs[0].duration.text
               console.log(time);
            }
            if (techs.length) {
                setTimeout(recursion, 1000);
            } else {
                console.log('DONE');
            }
        });
    }
}

在这里,recursiontechs数组中删除第一个元素,然后,当出现方向响应时,如果techs数组中仍然有元素,则{{ 1}}函数再次被调用。