如何执行功能后,所有的标记已被删除

How to execute function after all markers have been dropped?

本文关键字:删除 何执行 执行 功能      更新时间:2023-09-26

所以我使用这个代码dropMarkers在我的地图…该函数接受to地址字符串、from地址字符串和控制器的基本URL,其中存储了几个位置(包含name、lat、lng)。它会放下标记,点击这些标记会显示一个信息框,我可以从这个信息框跳转到控制器并开始编辑位置。

// RouteBoxer functions
function route(from, to, url) {
  // Clear any previous route boxes from the map
  if(debug)
    clearBoxes();
  // Convert the distance to box around the route from miles to km
  distance = parseFloat(distance);
  var request = {
    origin: from,
    destination: to,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }
  // Make the directions request
  var test = directionService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(result);
      // Box around the overview path of the first route
      var path = result.routes[0].overview_path;
      var boxes = routeBoxer.box(path, distance);
      if(debug)
        drawBoxes(boxes);
      for(key in boxes)
        {
          var swLat = boxes[key].getSouthWest().lat();
          var swLng = boxes[key].getSouthWest().lng();
          var neLat = boxes[key].getNorthEast().lat();
          var neLng = boxes[key].getNorthEast().lng();
          if(!isNaN(swLat) || !isNaN(swLng) || !isNaN(neLat) ||!isNaN(neLng)) {
            $.ajax({
              url: url,
              type: 'POST',
              dataType: 'json',
              data: {
                swLat: swLat,
                swLng: swLng,
                neLat: neLat,
                neLng: neLng
              },
            })
            .done(function( data ) {
              dropMarkers(data);
              console.log(markers.length);
            })
            .fail(function() {
              //console.log( "error" );
            })
            .always(function() {
              //console.log( "complete" );
            });
          }
        }
    } else {
      alert("Directions query failed: " + status);
    }
  });
}

dropMarkers基本上在地图中设置标记,并将其添加到数组变量var markers = []。我想要一些代码执行一旦所有的标记已被删除,但奇怪的是,我无法弄清楚如何做到这一点。我试着在for循环的末尾放一个alert(‘All markers dropped, No. of markers:’ + markers.length),但它在标记被删除之前就执行了,并显示0。我甚至试着把这个放在这个路由函数的最后一行,它给出了相同的行为。然而,console.log(markers.length)工作并逐渐向我展示标记数组正在填充,所以我正在寻找一种方法来调用函数时,最后一组标记被丢弃。

我读取了另一个堆栈溢出答案,并在我的init()块中尝试了此代码。

google.maps.event.addListener(directionsRenderer, 'directions_changed',function(){
   if(this.get('directions')){
     alert(‘All markers dropped, No. of markers:’ + markers.length)
   }
  });

这也过早地执行并显示0标记,即在标记被删除之前。如何调用一个函数后,所有的标记已被删除?由于

我能够解决这个问题。把它添加到init函数中就成功了。

$( document ).ajaxStop(function() {
  alert(markers.length);
});

逻辑是for循环执行得很快,并对一些ajax请求进行排队。这就是为什么在循环末尾添加警报显示为0的原因。ajax请求开始的时间稍晚,并且删除了标记。它的工作,当我添加async: false到ajax块,但这阻止了UI,所以我反而添加了ajaxStop到init块,它解决了这个问题。

希望这篇文章能帮助到其他遇到这个问题的人