Search code examples
leafletmarkerclusterer

Iterate a Leaflet marker cluster group and update the titles of the markers


       Self.companyMarkersClusterGroup.eachLayer(function(layer){
            const companyData = layer.options.companyData;

            layer.title = GetCompanyMapMarkerTitle(companyData);  
          });

I am trying to iterate over all markers in a Leaflet marker cluster group and update their titles.

The code above does not seem to work. What am I doing wrongly?

Could it be that the inner loop variable layer is a local deep copy from the marker, so that updating it does not update the marker? If so, how do I update the marker?


Solution

  • If by "title", you mean the native tooltip / title option on Marker icon that comes when you instantiate the Marker like that:

    L.marker(latLng, {
      title: "marker icon native tooltip"
    });
    

    ...then you need to update the Marker options title, as well as fiddle with its current icon title (if any) to update it immediately (in case the icon is currently displayed on map):

    const newTitle = "new title content";
    layer.options.title = newTitle;
    const icon = layer.getElement();
    if (icon) {
      icon.title = newTitle;
    }
    

    Note that if the native tooltip is currently displayed (i.e. if the user mouse is currently hovering the icon), the browser may not update the content before it disappears and reappears again.