Как добавить и удалить кластеры маркеров на листовой карте? - PullRequest
0 голосов
/ 25 ноября 2018

Я использую рыночный кластер листовки , и я устанавливаю маркеры в качестве круговых маркеров.

Версия листовки: leaflet@1.3.1

Версия кластера листовок: markercluster@1.3.0

NOTE

$.fn.almDone... и $.fn.almEmpty... - это только некоторые функции, которые я использую для своих обратных вызовов ajax

Я рисую некоторые маркеры на карте, если у нас есть результаты, и очищаю маркеры, которые мы нарисовали, если при втором обратном вызове у нас будет ноль результатов.Или просто сообщите пользователю, что мы получили ноль результатов и, следовательно, ноль маркеров.

У нас есть 2 массива со значениями, в которых я получаю координаты:

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');
}

Вышеприведенное работает, если у нас сначала есть результаты, а затем мы делаем другой поиск и у нас нулевые результаты, но если мысначала мы выполнили поиск, и мы получили zero results, затем у нас будет ошибка:

Uncaught ReferenceError: circles is not defined

И это правильно, потому что, поскольку мы попадаем в empty function, мыпопробуйте clear the markers, который мы никогда не определяли, поскольку мы никогда не входили в функцию маркеров рисования, где мы определяем circles.

Я очень запутался в том, как нарисовать маркеры и сделать var circles доступным в обоих случаях.

ps Рад всем, кто улучшил логику независимо от вопроса вопроса

1 Ответ

0 голосов
/ 25 ноября 2018

Я бы посоветовал поместить circles в качестве переменной вне области действия любой функции через var circles = undefined;.Обратите внимание, что проблема не в том, что окружности undefined, а в том, что они не определены, то есть не распознаются как переменные.

Затем установите его, как в drawMarkers.

На clearMarkers перед вызовом removeLayer проверьте if (circles), чтобы убедиться, что оно определено.Затем снова установите значение undefined после вызова removeLayer.

...