August
August

Reputation: 1819

Leaflet js dealing with a lot of markers in a single co-ordinate

I am using leafletjs and leafletjs marker clustering to display where my friends live. The problem is that some of them life in a same house, so the coordinates for multiple markers are the same. Issue occurs when there is more than 50 friends living in the same place.

Is there any way, that the markers could be hidden and when a cluster is clicked it would display a table containing all of the names?

My code for adding markers:

export function markersFromData(map, markers) {
  return (data) => {
    const markerList = [];
    data.map((v) => {
      const title = v.name;
      const marker = L.marker(new L.LatLng(v.latitude, v.longitude), {
        opacity: 0,
      });
      marker.bindPopup(title);
      markerList.push(marker);
      return markers.addLayer(marker);
    });
    map.addLayer(markers);
    // eslint-disable-next-line
    const group = new L.featureGroup(markerList);
    map.fitBounds(group.getBounds());
  };
}

Map example

enter image description here

Thank you for your time.

Upvotes: 3

Views: 2546

Answers (1)

ghybs
ghybs

Reputation: 53205

A clean solution would be instead of building one marker per data item (i.e. friend), to first group them by matching position.

Then build 1 marker per position, with metadata reflecting the number of items in that position and list of associated names.

Then in the Leaflet Marker cluster group, use the iconCreateFunction to customize the displayed number to sum these number of friends instead of number of child markers.

Upvotes: 1

Related Questions