Atlaslog / Field Notes / Leaflet containers & layers
Field note · Leaflet containers & layers
Each search adds another set of markers that cannot be removed
Quick answer
Every search creates new L.marker instances and adds them to the map without clearing the previous set, so markers stack, popups multiply and memory climbs. clearLayers does not help when stale marker references are still used.
Symptom
- Searching the same station five times leaves five overlapping markers whose icons look darker and fuzzier.
- One click opens five identical popups.
- Old results remain after changing the filter and memory keeps climbing across sessions.
Checklist
- Count markers with map.eachLayer and compare with results.length.
- Check whether each search calls map.addLayer(L.marker(...)) without clearing.
- Check whether clearLayers runs on a group the markers were never added to.
- Check whether stale marker references are reused after removal.
Fix
Keep one L.layerGroup().addTo(map), call clearLayers() before each render and add new markers to the group; for in-place updates reuse a marker pool with setLatLng and bindPopup.
Code
var count = 0;
map.eachLayer(function (layer) {
if (layer instanceof L.Marker) count++;
});
console.log('地图上的标记数', count, '结果数', results.length);var resultLayer = L.layerGroup().addTo(map);
function renderResults(results) {
resultLayer.clearLayers();
results.forEach(function (r) {
var marker = L.marker([r.lat, r.lng])
.bindPopup(r.name + '<br>' + r.address);
resultLayer.addLayer(marker);
});
}
renderResults(initialResults);
Watch out
- Calling map.removeLayer on a marker that was never added silently does nothing and leaves the visual duplicate.
- Trimming an index-based marker pool without removing markers from the map leaves orphans on screen.
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Atlaslog (2026). Each search adds another set of markers that cannot be removed. https://www.jingweizhi.com/en/cookbook/leaflet-duplicate-addlayer.html (accessed 2026-11-03).