【问题标题】:Passing Variable in google Service function在谷歌服务函数中传递变量
【发布时间】:2014-06-30 18:53:33
【问题描述】:

我正在使用 Google API 的 DistanceMatrixService 我试图在调用 getDistanceMatrix 函数时传递变量 'resto',这样当我得到响应时,我可以进一步使用该变量。 我的函数如下所示:

                var service = new google.maps.DistanceMatrixService();
                var resto = listRestaurant[i];
                service.getDistanceMatrix({
                    origins: [ new google.maps.LatLng(locationCurrent.coords.latitude, locationCurrent.coords.longitude) ] ,
                    destinations: [ resto.address ],
                //Here i am trying to pass the variable 'resto'
                },function ( response , status , resto ){
                    if (status != google.maps.DistanceMatrixStatus.OK) {
                        alert('Error was: ' + status);
                    } else {
                        if( response.rows[0].elements[0].distance !=null  ){
                            //Further use variable
                            console.log( resto );
                            callGeocoder( resto  );
                        }
                    }
                });

但是日志返回'未定义变量'

我做错了什么?

【问题讨论】:

    标签: javascript google-maps google-api


    【解决方案1】:

    你没有传递变量,你定义了一个函数参数。

    参数会在API内部传递,传递的参数只有一个DirectionsResult和一个DirectionsStatus,没有办法传递额外的参数。

    您可以使用匿名函数使变量在回调中可用:

                 var service = new google.maps.DistanceMatrixService();
    
                (
                  function(resto){
                    service.getDistanceMatrix({
                      origins: [ new google.maps.LatLng(locationCurrent.coords.latitude, 
                                                        locationCurrent.coords.longitude) ] ,
                      destinations: [ resto.address ],
                        //note:travelMode is required too
                      travelMode: google.maps.TravelMode.DRIVING
                    },function ( response , status ){
                    if (status != google.maps.DistanceMatrixStatus.OK) {
                        alert('Error was: ' + status);
                    } else { 
                        if( response.rows[0].elements[0].distance !=null  ){
                            //Further use variable
                            console.log( resto );
                            callGeocoder( resto  );
                        }
                    }
                    });
                  }
                )(listRestaurant[i]);
    

    【讨论】:

    • 聪明人!多谢!我以前从未见过这种语法。 (注意:是的,谢谢,我已将其从问题中删除,因为它不相关)
    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多