javascript - 回调函数未按预期工作

标签 javascript function google-maps-api-3 asynccallback

我在编写回调函数以从 google direction api 发出的异步请求中获取值时遇到困难,我在这里需要的是编写一个回调函数,让我在异步请求完成时获得时间。我想自己做,但我只是不明白为什么它不起作用,按照我在这个网站上看到的一些例子,这应该是可行的。

这是我的回调函数

function getTime(myVar){alert(myVar);}

调用回调函数的函数

function travellingTime(Origin, Destination, callback) {
    var myVar;
    var directionsService = new google.maps.DirectionsService();
    var request = {
        origin: Origin,
        destination: Destination,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            // Display the distance:
            //alert(response.routes[0].legs[0].distance.value + " meters");
            // Display the duration:
            //Time = (response.routes[0].legs[0].duration.value / 60);

            myVar = (response.routes[0].legs[0].duration.value / 60);
            callback(myVar);
        }
    });
}

在按钮上触发 Action

<button onclick="travellingTime('portlouis','vacoas',getTime())">TSP</button>

当警报时,我仍然得到 myVarundefined

最佳答案

你正在调用getTime并传递结果,只是传递它而不调用它。像这样(删除一对括号)。

<button onclick="travellingTime('port louis','vacoas',getTime)">TSP</button>

关于javascript - 回调函数未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49271636/

相关文章:

javascript - 如何执行 Google Maps 基于区域的聚类或标记重叠

javascript - 无法使用事件监听器阻止按键

javascript - Google Maps API v3 中是否有等效的 GDownloadUrl 函数

javascript - 为什么 Meteor 对这个 IronRouter 代码感到暴躁?

r - 如何使用 get() 构建复杂的变量模型

c++ - "int& foo()"在 C++ 中是什么意思?

c++ - 有人可以解释一下吗?

javascript - Google.maps.Map Javascript API V3 与 jquery 的兼容性

javascript - 创建按钮 onclick 函数以充当箭头键的作用

javascript - 如何从普通的 JS 函数调用 jQuery 函数?