Использование Algolia и Leaflet, чтобы показать результаты, основанные на том, что показывает карта.Наличие ошибок при перетаскивании и масштабировании с использованием setQueryParameter - PullRequest
0 голосов
/ 22 ноября 2018

Я создаю страницу, которая показывает элементы на карте и результаты, полученные из Алголии.В настоящее время я могу искать, добавлять фасеты и ползунок даты, который меняет карту.Моя текущая ошибка заключается в том, что когда я увеличиваю или перетаскиваю изображение, я создал функцию, которая выполняет поиск по базе Algolia на insideBoundingBox, страница получает границы, затем центрирует карту, а затем увеличивает масштаб, чтобы показать результаты.Но затем это повторяется несколько раз.Какой лучший способ вылечить это?Поставить задержку после обработки зума?Или мне нужно указать уровень масштабирования, чтобы он не менялся?

Это мой код:

search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item: document.getElementById('hit-template').innerHTML,
      empty: "We didn't find any results for the search <em>\"{{query}}\"</em>"
    },
    transformItems: function(items) {
      renderMap(items);
      return items.slice(0, curentResultsPerPage);
    },
  })
);

const map = L.map(
  'mapid', {
    renderer: L.canvas(),
    zoom: 18,
    keepInView: true,
    dragging: !L.Browser.mobile,
  }
).setMaxZoom(18).setMinZoom(2);

let markers = [];

function renderMap(items) {
  if (typeof clusters !== 'undefined') {
    clusters.clearLayers();
    clusters.getBounds();
  }

  // remove current markers
  markers.forEach(marker => marker.remove());
  // clear the markers
  markers = [];

  // create cluster group
clusters = L.markerClusterGroup({
  chunkedLoading: true,
  showCoverageOnHover: false,
  maxClusterRadius: 60,
});
  // iterate through search results
  for (var i = 0; i < items.length; i++) {
    // get result
    var item = items[i];
    var geo = item._geoloc;
    // create marker
    var marker = L.marker([geo.lat, geo.lng], {icon: myIcon});

    // create marker popup
    marker.bindPopup(
      '<a href="' + item.field_relative_url + '">' + '<img class="thumbnail__map__icon" src="#"></a>'
    );

    // add the marker to the markers array
    markers.push(marker);

    // add the marker to the cluster group
    clusters.addLayer(marker);
  }

  // add the cluster group to the map
  map.addLayer(clusters);

  if (markers.length) {
    map.fitBounds(L.featureGroup(markers).getBounds());
  }
}

map.on('zoomend dragend', function (event) {
  var bnds = map.getBounds();
  var boundingBox = [
    bnds._northEast.lat,
    bnds._northEast.lng,
    bnds._southWest.lat,
    bnds._southWest.lng
  ];
if (bnds._northEast.lat > -180 && bnds._northEast.lat < 180 &&
  bnds._northEast.lng > -180 && bnds._northEast.lng < 180 &&
  bnds._southWest.lat > -180 && bnds._southWest.lat < 180 &&
  bnds._southWest.lng > -180 && bnds._southWest.lat < 180) {

  search.helper.setState(search.helper.state.setQueryParameter('insideBoundingBox', [boundingBox])).search()
}
});
// Main search function.
search.start(); 
...