限制侦听器在设定的时间段内可以触发的次数

Limit the number of times a listener can fire in a set period?

本文关键字:时间段 侦听器      更新时间:2023-09-26

继我昨天的一个问题之后:

谷歌路线服务,带航点返回ZERO_RESULTS

莫尔博士说,directions_changed听众会再次开火。他们是对的。它无限地发射。我想知道是否有更好的地方来放置这个侦听器,或者是否有办法限制它在设定的时间段内允许触发的次数。

function route(waypoint) {
distance = 5;   // Default distance
if(waypoint){
    var request = {
        origin: document.getElementById("search-input-from").value,
        destination: document.getElementById("search-input-to").value,
        waypoints: waypoint,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
}
else{
    var request = {
        origin: document.getElementById("search-input-from").value,
        destination: document.getElementById("search-input-to").value,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
}
var directionRendererOptions = { draggable: true };
// Make the directions request
directionService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setOptions(directionRendererOptions); 
        directionsDisplay.setDirections(result);
        directionsDisplay.setMap(map);
        var path = result.routes[0].overview_path;
        // more code here that won't matter
    }
    else {
            alert("Directions query failed: " + status);
        }
     //listener for dragged route/polyline
google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){
            var waypoints = directionsDisplay.getDirections().routes[0].legs[0].via_waypoints||[];
            for(var i=0;i<waypoints.length;++i){
               waypoints[i]={stopover:true,location: waypoints[i]}
            }
            route(waypoints);
        });
    });
 }

编辑:应该更好地解释自己。基本上,当我试图重新绘制路线时,我得到了一个无限循环directions_changed.

另外,对于任何关注这个问题的人来说,我真的认为反对票是没有必要的。我不缺乏研究或努力,文档的航点部分很糟糕,而且他们从未尝试通过 LatLng 对象使用航点。他们只使用位置。

当你调用route(waypoint)时,设置一个标志。 当directions_handler函数运行时,清除标志,不要重新呈现方向。

  var directionsRedraw = false;
  google.maps.event.addListener(directionsDisplay, 'directions_changed', function(){
    if (directionsRedraw == false) {
      directionsRedraw = true;
      var waypoints = directionsDisplay.getDirections().routes[0].legs[0].via_waypoints||[];
      for(var i=0;i<waypoints.length;++i){
        waypoints[i]={stopover:true,location: waypoints[i]}
      }
      route(waypoints);
    } else { 
      directionsRedraw = false;
    }
  });