Each move will result in the continuous addition of markers within the boundaries, potentially leading to map overload and browser crashing.
To prevent this, consider the following steps:
- Implement a check for optimal zoom levels, advising against loading entries below 12 to avoid exceeding request size limits (optional).
- Load only new markers that are not already within the current bounds.
- Terminate any ongoing requests immediately.
- Create a request with extended bounds (10% increase) to optimize marker loading frequency.
- Upon completing the request, transfer existing layers to an array, filtering out those present in the request results. The remaining layers in the array need removal while the new ones must be added to the map.
Note: This code has not been tested. It is recommended to replace Ajax/jQuery requests with vanilla fetch requests.
var runningRequests = [];
var allLayers = [];
function initLoad() {
// Add event listeners to load new layers
map.on('moveend',mapMove);
map.on('zoomend',mapMove);
// Load initial layers
if (map.getZoom() > 12) {
loadLayers(map);
}
}
function mapMove() {
if (map.getZoom() > 12) {
if (areaBounds.contains(map.getBounds()) === false) {
loadLayers()
}
}
}
function loadLayers() {
areaBounds = map.getBounds().pad(0.15);
if(runningRequests.length > 0){
for (var i in runningRequests) {
runningRequests[i].abort();
delete runningRequests[i];
}
}
var req = $.ajax(options).done(function(json) {
var layersToRemove = allLayers;
len = json.length;
var layersToAdd = [];
json.forEach((obj) => {
var coords = obj.coordinates;
var filteredLayers = layersToRemove.filter(function (layer) { return !layer.getLatLng().equals([coords[1], coords[0]]) });
if(filteredLayers.length === layersToRemove.length){
layersToAdd.push(obj);
}
layersToRemove = filteredLayers;
});
layersToRemove.forEach((layer) => {
map.removeLayer(layer);
});
addLayer(layersToAdd);
});
runningRequests.push(req);
}
function addLayer(geoJsonLayers){
var featureCollection = {
"type": "FeatureCollection",
"features": []
};
featureCollection.features = geoJsonLayers;
var geoJson = L.geoJSON(featureCollection)
.bindPopup((layer) => layer.feature.properties.name)
.addTo(map);
geoJson.getLayers().forEach((layer) => {
allLayers.push(layer);
});
}