Assigning ID to marker and adding and removing from cluster using leaf.js

i am new to leaflet and clusters but I have managed to get some custom markers on a map with leaflet.js maps and cluster.

All is good apart from I cant seem to work out how to remove a marker as it does not seem to assign an ID number or anything. I have tried to use this sort of thing to add an ID but not getting anywhere and hence why I have not attempted to remove the marker.

var user_id = '101';

 var marker[user_id] = L.marker(new L.LatLng(a[0], a[1]), {
 icon: client,
 title: title
 });

I have the data in this format :-

var addressPoints = [
[52.4134975, -1.5131260, "101", "YES"],
[52.4904975, -1.5151260, "102", "NO"],
[52.4734975, -1.5171260, "103", "BUSY"],
[52.4194975, -1.5181260, "104", "NO"],
[52.4264975, -1.5130460, "105", "YES"],
[52.4284975, -1.5191210, "106", "YES"],
[52.4014975, -1.5191949, "107", "BUSY"],
[52.4299975, -1.5110060, "108", "NO"]
]

I use this code to loop through them and add to the map with custom marker, it works good but if I want to remove or change the CSS on one I cant locate it.

var map = L.mapbox.map('map')
      .setView([52.450439, -1.729660], 14)
      .addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));

    var markers = new L.MarkerClusterGroup();



    for (var i = 0; i < addressPoints.length; i++) {
            var a = addressPoints[i];
            var online_status = a[3];
            var user_id = a[2];
            var imgts = a[2];
            var title = a[2];

// Add online users //  

    if  (online_status === "YES") {
    console.log('online');
                var client = L.divIcon({
                className: 'location-pin',          
                html: '<img id"operatorimg" src="img/'+imgts+'.jpg"><div class="pin online"><div class="pulse"></div>',
                iconSize: [30, 30],
                iconAnchor: [18, 30]
        });
        
        var marker = L.marker(new L.LatLng(a[0], a[1]), {
            icon: client,
            title: title
        });
    
    }

        marker.bindPopup(title);
        markers.addLayer(marker);
    }

    map.addLayer(markers);

I have tried to assign some sort of ID when looping but its not having it? Am i taking the wrong approach? Any help is appreciated and sorry if I have not put this up correctly, I have just joined.

Thanks

Answer

Leaflet markers are classes, so one thing you can try is to add a property to the class and find the marker by that property. For instance, if you have a marker and the data for the marker contains a name, you can add a name property to the marker. Then, you need to cycle through the layers in the markerClusterGroup to find the marker you want to remove. According to this SO answer, L.markerClusterGroup extends Leaflet’s layerGroup, so you can use the eachLayer method to iterate each layer in the group. Then, you can find the desired marker by the property you assigned earlier and use the removeFrom method to remove it from the map. Here’s an example using Leaflet’s layerGroup:

import L from 'leaflet';

var mymap = L.map('mapid').setView([51.505, -0.09], 12);

var tile = {
  base: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
  attr: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
};
var tileLayer = L.tileLayer(tile.base, {
  attribution: tile.attr,
  maxZoom: 18,
  tileSize: 512,
  zoomOffset: -1,
}).addTo(mymap);

// Create a group for the layers:
var markerLayer = L.layerGroup().addTo(mymap);

var pointsForMarker = [
  { name: 'Center Of London', lat: 51.5, lng: -0.09 },
  { name: 'Big Ben', lat: 51.5007, lng: -0.1246 },
  { name: 'Buckingham Palace', lat: 51.5014, lng: -0.1419 },
];

var originalMarkerStyles = `
  background-color: black;
  width: 3em;
  height: 3em;
  display: block;
  left: -1.5em;
  top: -1.5em;
  position: relative;
  border-radius: 3rem 3rem 0;
  transform: rotate(45deg);
  border: 1px solid #FFFFFF`;

var myIcon = L.divIcon({
  className: 'custom-icon',
  iconAnchor: [0, 24],
  labelAnchor: [-6, 0],
  popupAnchor: [0, -36],
  html: `<span style="${originalMarkerStyles}"></span>`,
});

// Add points to the map:
pointsForMarker.forEach((point) => {
  var marker = L.marker(point, { icon: myIcon }).addTo(markerLayer);
  marker.bindPopup(`NAME: ${point.name}`).openPopup();
  // Add a 'name' property to the marker class:
  marker.name = point.name;
});

var dismissBtn = document.querySelector('#dismissBtn');
dismissBtn.addEventListener('click', () => {
  // When button clicked, user prompted to enter name for marker to dismiss:
  var markerToDismiss = prompt(
    'Enter name of marker to dismiss:',
    'buckingham palace'
  );
  // Iterate through each layer (marker) in layerGroup:
  markerLayer.eachLayer((layer) => {
    if (markerToDismiss) {
      // If the name property on the marker matches the name entered in the prompt:
      if (
        layer.name.trim().toLowerCase() === markerToDismiss.trim().toLowerCase()
      ) {
        // Remove the marker:
        layer.removeFrom(markerLayer);
      }
    }
  });
});

// To change the style of a custom Icon:
var colorBtn = document.querySelector('#colorBtn');
colorBtn.addEventListener('click', () => {
  var markerToChange = prompt('Enter name to change marker color:', 'big ben');
  markerLayer.eachLayer((layer) => {
    if (markerToChange) {
      if (
        layer.name.trim().toLowerCase() === markerToChange.trim().toLowerCase()
      ) {
        var newStyle = `
          background-color: red;
          width: 5em;
          height: 5em;
          display: block;
          left: -1.5em;
          top: -1.5em;
          position: relative;
          border-radius: 3rem 3rem 0;
          transform: rotate(45deg);
          border: 1px solid #FFFFFF`;
        var newIcon = L.divIcon({
          className: 'custom-icon',
          iconAnchor: [0, 24],
          labelAnchor: [-6, 0],
          popupAnchor: [0, -36],
          html: `<span style="${newStyle}"></span>`,
        });
        // Use the L.marker.setIcon to set an icon with the style changes:
        layer.setIcon(newIcon);
      }
    }
  });
});

Here is a demo set up on StackBlitz for you to play with