Atlaslog
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.

Last verified 2026-11-03 · Multiple versions · Cite this page
Applies to: Leaflet
Symptom
Checklist
  1. Count markers with map.eachLayer and compare with results.length.
  2. Check whether each search calls map.addLayer(L.marker(...)) without clearing.
  3. Check whether clearLayers runs on a group the markers were never added to.
  4. 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
All 120 field notesChinese originalRunnable examples
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Cite this page

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).