0

我正在尝试根据从 .getJSON 检索到的数据动态更改用于计算谷歌地图路线的功能。我尝试在 .done 函数下包含大部分函数 calcRoute(),但我在 javascript 控制台中的属性航点中收到错误。我不知道该怎么做,因为当我不包含 .done 下的大部分函数时,数组仍然是空白的(使用 .getJSON 进行异步调用。这里是给你一个更好的主意的代码:

    function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var waypts = [];
        var data = $.getJSON("/westcoast_map.php", {
            westcoast_id: $('.opener').data('westcoast_id')
        }, function(json) {
            return json[1];
        });

        data.done(function(theData) {
            waypts = theData[1];
            console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...

            var request = {
                origin: start,
                destination: end,
                waypoints: waypts,
                optimizeWaypoints: true,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };

            directionsService.route(request, function(response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    var route = response.routes[0];
                    var summaryPanel = document.getElementById('directions_panel');
                    summaryPanel.innerHTML = '';
                    // For each route, display summary information.
                    for (var i = 0; i < route.legs.length; i++) {
                        var routeSegment = i + 1;
                        summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
                        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
                        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
                        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
                    }
                }
            });

        });
    }
4

1 回答 1

0

我仍然不确定你的问题是什么,因为你展示的代码至少应该从逻辑部分工作。但是有些部分不清楚您要达到什么目标:

    var data = $.getJSON("/westcoast_map.php", {
        westcoast_id: $('.opener').data('westcoast_id')
    }, function(json) {
        return json[1];
    });

如果您期望这里data 会变成json[1],那么您的假设是错误的。 $.getJSON总是返回jQuery XHR。稍后浏览器接收到数据时会调用回调函数。

这里有一个小例子来理解 async 是如何工作的:回调函数 1 和 2 在客户端收到请求的响应时被调用,但不是在原始脚本完全执行doSomethingElse()之前调用,所以总是在回调函数 1 和 2 之前调用被执行。回调函数 1 和 2 的执行顺序取决于哪个响应先到达。

var test = [];
preparesSomeStuff();

$.getJSON("someurl1",{},function() {
   //Callback Function 1

});

doSomething();

$.getJSON("someurl2",{},function() {
   //Callback Function 2
});


doSomethingElse();
//<<END OF SCRIPT>>

如果您不想将整个代码包含在回调函数中(例如因为可读性),您可以通过以下方式进行操作:

function calcRoute() {
    var start = document.getElementById('start').value;
    var end = document.getElementById('end').value;
    var waypts = [];
    $.getJSON("/westcoast_map.php", {
        westcoast_id: $('.opener').data('westcoast_id')
    }, function(theData) {
        calcualteRoute(theData[1], start, end);
    });

    //if you place code here it will be executed before displayResult will be called because getJSON is async
}


function calcualteRoute(waypts, start, end) {
    console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...

    var request = {
        origin: start,
        destination: end,
        waypoints: waypts,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            displayResult(response,status);
        }
    });

    //if you place some code here it will be executed BEFORE displayResult will be called, because 
    //directionsService.route is async

}

function displayResult(response, status) {
    directionsDisplay.setDirections(response);
    var route = response.routes[0];
    var summaryPanel = document.getElementById('directions_panel');
    summaryPanel.innerHTML = '';
    // For each route, display summary information.
    for (var i = 0; i < route.legs.length; i++) {
        var routeSegment = i + 1;
        summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
        summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
        summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
        summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
    }
}
于 2013-03-05T07:07:31.063 回答