我正在创建一个页面,用于显示地图上的项目以及从Algolia生成的结果。目前,我可以搜索,添加构面和可更改地图的日期滑块。我当前的错误是,当我放大或拖动时,我创建了一个函数,该函数基于insideBoundingBox搜索Algolia,页面将获得边界,然后将地图居中,然后放大以显示结果。但这会重复多次。 解决此问题的最佳方法是什么?处理缩放后是否延迟?还是我必须指定缩放级别以使其不改变?
这是我的代码:
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();