0

我有函数在执行时会根据一组值在地图上绘制路线。我正在使用谷歌地图*方向渲染*。根据我所见的研究,要在地图上渲染多条路线,我需要为数组中的每条路线创建一个方向渲染

我正在尝试为数组中的每条路线创建一个方向渲染,所以我决定将变量的名称与索引“i”连接起来。这不起作用。

我将Directions Render对象创建为一个数组,但是在访问数组以填充点时出现错误 - TypeError: can't convert undefined to object DirectionsService[i] = new google.maps.DirectionsService();

如果我创建单独的方向渲染, 例如 DirectionsRender0,DirectionsRender1,DirectionsRender2 ...这工作正常,但是会有一个实例,我不确定会有多少方向渲染。

下面是我的代码示例:

function plotRoutes(){  

    var directionsDisplay = new Array();

    for (var i=0; i< startLoc.length; i++){

    var rendererOptions = {
        map: map,
        preserveViewport:true
    }
    directionsService[i] = new google.maps.DirectionsService();

    var travelMode = google.maps.DirectionsTravelMode.DRIVING;  

    var request = {
        origin: startLoc[i],
        destination: endLoc[i],
        travelMode: travelMode
    };  
        directionsDisplay[i] = new google.maps.DirectionsRenderer(rendererOptions);

        directionsDisplay[i].setMap(map);

        directionsService.route(request, function(response, status) {
        //console.log(response);

        if (status == google.maps.DirectionsStatus.OK){
            console.log(response);
            directionsDisplay[i].setDirections(response);

            }

        });
    }   
4

1 回答 1

1

问题是所有回调共享同一个变量“i”,并且在每个回调中,“i”的值将超过调用回调时的点数。

在单独的函数中创建回调,如下所示:

  function makeRouteCallback(disp) {
    return function(response, status) {
      console.log(response);
      disp.setDirections(response);
    };
  }

然后设置回调:

  directionsService.route(request, makeRouteCallback(directionsDisplay[i]));

That assures that the actual callback function used by the API will be the correct member of your array. The reference to "i" is evaluated at the time the callback is established, not when it's actually called. At that point, the callback function uses the stashed copy ("disp"), which will be private to each callback.

于 2013-08-05T19:05:19.883 回答