如何在leaflet地图上添加和删除标记聚类?

4
我正在使用 leaflet market cluster,并将标记设置为圆形标记。

Leaflet 版本:leaflet@1.3.1

Leaflet 群集版本:markercluster@1.3.0

注意

$.fn.almDone...$.fn.almEmpty... 只是我用于 ajax 回调的一些函数。

如果有结果,我会在地图上绘制一些标记,并在第二个回调中清除已绘制的标记,如果没有结果,则告诉用户我们没有结果,因此没有标记。

我们有两个包含值的数组,我从中获取坐标:

var longitude = [];
var latitude = [];
var count = [];

我们在开始时将变量设置为stopAjax true
var stopAjax = true;

点击后,我们开始搜索并将stopAjax设置为false

$(".alm-filters--button").on("click", function(){
  stopAjax = false;
});

这就是基本的逻辑,现在我们定义两个函数:

// This is run when we finish the call and we have results
// So on the callback we run the function to draw the markers

$.fn.almDone = function(alm){
  drawMarkers();
};

// Let's draw the markers

function drawMarkers() {

  // This is the logic to read latitude and longitude arrays
  // and push to a new array the two values as pair of coords
  // eg. 4.66, 4,5555 

  var i;
  for (i = 0; i < longitude.length; ++i) {
    pair=[ parseFloat( latitude[i] ) , parseFloat(  longitude[i]  ) ]
    count.push(  pair );
    $("#searchNations").removeAttr("disabled");
    $(this).attr("disabled", "disabled");
    var myYears = $('#years').val();
    $("#ajax-load-more ul").attr("data-meta-value", myYears);
  };

  // We check if we said to run ajax
  // and if so draw the markers
  // for myself I had also to retrieve those coords
  // and place them in individual inputs for the form

  if(stopAjax == false) {
    L.MarkerCluster.include({
      spiderfy: function(e) {
        var childMarkers = this.getAllChildMarkers();
        this._group._unspiderfy();
        this._group._spiderfied = this;

        // Fill the markersList.

        markersList.innerHTML = childMarkers
        .map((marker, index) => `<li>Marker ${index + 1}: ${marker.getLatLng()}</li>`)
        .join('');

        // If there are any childMarkers
        // draw the cluster and run a form

        if(childMarkers.length > 0) {
          // Match the lat and lng numbers from the string returned by getLatLng()
          const [lat, lng] = `${ childMarkers[0].getLatLng() }`.match(/(-?\d+.\d*)/gi);  

          // Construct the required string value from the extracted numbers
          const requiredString = `${ lat }, ${ lng }`;

          // Use requiredString to populate the value attribute of the input field in OP

          // grab the coords in individual inputs
          // that's just for my specific case

          $("#longiTude").attr("value",lat);
          $("#latiTude").attr("value", lng); 

          // run a form to see results

          submitSearchForm();
        }
      },
      unspiderfy: function() {
        this._group._spiderfied = null;
      }
    });

    // this bit is for single marker
    // we want to add a click to run the form 
    // also for the single marker and grab the coords 
    // and place them in inputs for the form

    var mcg = L.markerClusterGroup().addTo(map);

    circles = new L.MarkerClusterGroup();
    for (var i = 0; i < count.length; i++) {
      var a = count[i];
      var circle = new L.CircleMarker([a[0], a[1]]);
      circles.addLayer(circle);
      circle.on('click', function (e) {
        var curPos = e.target.getLatLng();
        $("#longiTude").val(curPos.lat);
        $("#latiTude").val(curPos.lng);
        submitSearchForm();
      });
    }

    // we add the markers to the map
    map.addLayer(circles);

    // we empty the arrays for the future calls

    count = [];
    longitude = [];

    // we set again stopAjax var to true to reset
    stopAjax = true;   
  }
}

然后是零结果函数

//This is run when we have zero results

$.fn.almEmpty = function(alm) {
 stopAjax = true;
  clearMarkers();
};

// We empty the arrays and we
// clear the previously drawn markers

function clearMarkers(stopAjax) {
  if(stopAjax == true) {
    count = [];
    longitude = [];
    map.removeLayer(circles);
  }
  // if zero results, we launch a modal to advise user
  $('#zeroResults').modal('show');
}

如果我们先有了搜索结果,然后再进行另一次搜索并且结果为零,那么上述方法是可行的。但是,如果我们首先进行了搜索并且得到了“零结果”,那么就会出现错误:
Uncaught ReferenceError: circles is not defined
这是正确的,因为自从我们进入“空函数”以来,我们尝试清除标记,但我们从未定义过它们,因为我们从未进入过定义圆形的绘制标记函数。
我对如何绘制标记并使“var circles”在两种情况下都可用感到非常困惑。
引用:

附言:欢迎任何人改善逻辑,无论问题如何

1个回答

2
我会考虑通过 var circles = undefined;circles 作为变量放在函数范围之外。请注意,问题不是 circlesundefined,而是它没有被定义,即未被识别为变量。
然后像在 drawMarkers 中一样设置它。
在调用 removeLayer 之前的 clearMarkers 中,检查 if (circles) 是否已定义。然后在调用 removeLayer 后再次将其设置为未定义。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接