jperelli / vue2-leaflet-markercluster

markercluster plugin extension for vue2-leaflet package
MIT License
132 stars 55 forks source link

dynamic custom icon is changing on zoom - maybe some ID needed #39

Closed donni106 closed 4 years ago

donni106 commented 4 years ago

Hi, clusters are working for my use case pretty well, thanks. But: I have a special icon to show for clustered points. I do not want to show the number of items on that point, just a random icon. This icon is created dynamically inside of iconCreateFunction:

iconCreateFunction: () => {
  // random number between 1 and 5
  const randomNumberMultiMarker = () => Math.floor(Math.random() * 5) + 1;
  return L.icon({
    iconUrl: `${iconPath}/multimarker-${randomNumberMultiMarker()}.png`,
    iconAnchor: [10, 50]
  });
}

My problem is, that this method is called when zooming in and out, which lets the icon change. I have not found any cluster ID to reference to for setting the same icon number after zooming. With an ID i could save icons to an object like a cache and use that in the method.

Any idea how to avoid updating the icon automatically? Is there or could there be an index or ID for the clusters?

donni106 commented 4 years ago

Ok, I found a solution with using .getLatLng to create a unique identifier!

iconCreateFunction: (cluster) => {
  // random number between 1 and 5
  const randomNumberMultiMarker = () => Math.floor(Math.random() * 5) + 1;
  // use the lat lng to create a unique id for caching icons,
  // otherwise they would be dynamically recreated on zooming for example
  const clusterLatLng = cluster.getLatLng();
  const clusterId = `${clusterLatLng.lat}-${clusterLatLng.lng}`;
  // check if there is a icon already saved for the lat-lng combination
  let clusterIcon = this.clusterIconsCache[clusterId];

  if (!clusterIcon) {
    clusterIcon = L.icon({
      iconUrl: `${iconPath}/multimarker-${randomNumberMultiMarker()}.png`,
      iconAnchor: [10, 50]
    });
    // save the created icon in the icons cache at position lat-lng combination
    this.clusterIconsCache[clusterId] = clusterIcon;
  }

  return clusterIcon;
}

Now I can zoom and the icons stay the same as created on first load.