Search code examples
javascriptleafletleaflet.markercluster

Leaflet markercluster markers and cluster icons both visible on load


Upon loading the map the pins and the markercluster icons are both visible. It is only after zooming to max that all pins break out and the clusters begin working as intended on zoom back out.

What am I doing incorrectly that would cause this issue?

current setup:

const markerCluster = Leaflet.markerClusterGroup({showCoverageOnHover: false})

//within a loop the markers are created:

() => {
  const pinBackground = item.current ? '#db2828' : '#3dcc4a'
  const interior = item.pin.icon_url
    ? `<img style="background: ${item.pin.color_code}" src=${item.pin.icon_url}>`
    : `<div class="mapPanelAbbreviation" style="background: ${item.pin.color_code}">${item.pin.abbreviation}</div>`
  const pinLayout = `<div class="mapPanelIconContainer" style="background:${pinBackground}">
      ${interior}
    </div>`

  let marker = Leaflet.marker(coord, {icon: Leaflet.divIcon({html: pinLayout})})
    .bindPopup(`<p class='pinText'>${item.taskId}</p><p class='pinDetails'>${item.title}</p>`)
    .addTo(this.currentMap)
    .addTo(this.markerGroup)

  markerCluster.addLayer(marker)
}

//then the markerCluster is added to the map

this.currentMap.addLayer(markerCluster)

when the map loads I see both the pins created (which should be contained in the markerCluster) and the cluster icon with the pin count displayed:

enter image description here

after the first zoom:

enter image description here

As always any direction and help is great appreciated, so thanks in advance!


Solution

  • Simply do not add your Markers to the map (or to any other Layer Group that is added to map), but only to your MarkerClusterGroup:

    let marker = Leaflet.marker(coord, {icon: Leaflet.divIcon({html: pinLayout})})
      .bindPopup(`<p class='pinText'>${item.taskId}</p><p class='pinDetails'>${item.title}</p>`)
      //.addTo(this.currentMap) // this duplicates your Markers
      //.addTo(this.markerGroup) // this also duplicates if markerGroup is added to map
    
    markerCluster.addLayer(marker)