多个谷歌地图方向请求返回所有请求的最后响应

Multiple Google Maps directions requests returning last response for all requests

本文关键字:请求 最后 响应 返回 谷歌地图 方向      更新时间:2023-09-26

我正在尝试使用谷歌地图方向服务返回同一路线的三种旅行方式(驾驶、步行和骑自行车)。我可以成功地循环遍历方法数组,并将它们放入相关请求中,但所有三个请求都返回bicycling的响应,bicycling是数组中的最后一个方法。这是因为发送给谷歌的请求是异步的吗?

有问题的代码似乎在这个代码的for each循环中:

directionsDisplay = new google.maps.DirectionsRenderer();
var origin = new google.maps.LatLng(51.5072, 0.1275);
var destination = new google.maps.LatLng(53.7997, 1.5492);
map = new google.maps.Map(document.getElementById('map-canvas'));
var request = {
    origin: origin,
    destination: destination
};
var methods = new Array("DRIVING", "WALKING", "BICYCLING");
var route = new Array();
$.each(methods, function(key, method) {
    request.travelMode = google.maps.TravelMode[method];
    console.log(request.travelMode);
    directionsService = new google.maps.DirectionsService();
    directionsService.route(request, function(response) {
        directionsDisplay.setDirections(response);
        route[method] = directionsDisplay.getDirections();
        console.log(route[method].routes[0].legs[0].steps[0].travel_mode);
        //console.log(route.routes[0].legs[0].duration.text);
        //console.log(Math.round(Math.round(route.routes[0].legs[0].distance.value/1000)*0.6214));
    });
});

请查看这个jsfiddle中的代码以找到完整的代码。将发送的方法打印在控制台中,然后是响应中包含的旅行方法。

request是一个引用,在使用该引用的任何地方,对该引用的所有更改都将可见。

创建请求的副本(使用所需的travelMode),并将此副本用作route() 的参数

directionsService.route($.extend({},
                                 request,
                                 {travelMode: google.maps.TravelMode[method]}), 
                        function(response) {/*your code */});

更新的小提琴:http://jsfiddle.net/FLT2n/5/