0

我有一条由多个子路线组合而成的路线。(子路线是指多个 DirectionsRenderer 对象)

我还有一个循环,我遍历所有 DirectionsRenderer 对象并将“directions_changed”事件附加到所有对象。

不幸的是,当我尝试测试拖动折线时会发生什么时,只有最后一个 DirectionsRenderer 对象会触发该事件。

这是我的代码的一部分:

for(var k=0; k<directionsRenderers.length; k++)
{

     var directionsRenderer = directionsRenderers[k];
     var a = registerDirectionsChangedEvent(k,directionsRenderer);  
}


function registerDirectionsChangedEvent(index, directionsRenderer)
{
    this.index = index;
    this.directionsRenderer = directionsRenderer;

    var that = this;
    var a = google.maps.event.addListener(this.directionsRenderer, "directions_changed", function()
    {
       var newStopPoint;
       var directionsResult = that.directionsRenderer.getDirections();
       var route = directionsResult.routes[0];
       var legs = route.legs;
       var legsIndex = 0;

       for(var i=0; i<legs.length; i++)
       {
          var cLeg = legs[i];
          var viaWaypoints = cLeg.via_waypoints;
          if(viaWaypoints.length > 0)
          {
             newStopPoint = viaWaypoints[0];
             if(that.index === 1) legsIndex += 9;
             else if(that.index === 2) legsIndex += 18;

             break;
          }
          legsIndex++;
      }

      addNewStopPoint(newStopPoint,legsIndex);
   });

    return a;
}

正如我在上面提到的,不仅最后一个 DirectionsRenderer 对象被触发,而且最后一个事件之前的那些没有实现默认行为。

也许你已经注意到我使用:

this.index = index;
this.directionsRenderer = directionsRenderer;

var that = this;

没有它的事件仍然无法正常工作。

我还尝试使用在循环中创建的函数,如下所示:

(function someFunction(a,b){//do something here})(a,b);

但仍然没有运气!

任何建议如何使它工作?

4

1 回答 1

0

使用函数闭包,这可能是重复的(未测试):

for(var k=0; k<directionsRenderers.length; k++)
{
     var directionsRenderer = directionsRenderers[k];
     var a = registerDirectionsChangedEvent(k,directionsRenderer);  
}


function registerDirectionsChangedEvent(index, directionsRenderer)
{
    var a = google.maps.event.addListener(directionsRenderer, "directions_changed", function()
    {
       var newStopPoint;
       var directionsResult = directionsRenderer.getDirections();
       var route = directionsResult.routes[0];
       var legs = route.legs;
       var legsIndex = 0;

       for(var i=0; i<legs.length; i++)
       {
          var cLeg = legs[i];
          var viaWaypoints = cLeg.via_waypoints;
          if(viaWaypoints.length > 0)
          {
             newStopPoint = viaWaypoints[0];
             if(index === 1) legsIndex += 9;
             else if(index === 2) legsIndex += 18;

             break;
          }
          legsIndex++;
      }

      addNewStopPoint(newStopPoint,legsIndex);
   });

    return a;
}
于 2013-05-15T13:29:37.067 回答