1

I am new to Leaflet and recently did a course on using Leaflet to make maps. I followed the instructions to implement leaflet marker cluster, but, when trying to extract data to fill the popup from my GeoJSON, each popup contains the same data.

While the marker clustering works very well and picks up all the point sin the GeoJSON, the data going into there popup is always the same!

The code I have used looks like this:

var markers = L.markerClusterGroup({
  showCoverageOnHover: false,
});

json.features.forEach(function (feature) {
  markers
    .addLayer(
      L.marker([
        feature.geometry.coordinates[1],
        feature.geometry.coordinates[0],
      ])
    )
    .bindPopup(feature.properties.Name);
});
map.addLayer(markers);

How can I get the relevant info onto each popup?

2

This is a problem with the parentheses, most likely an overlook.

You (most probably) wanted to bind a popup to each of the markers, e.g.

var marker = L.marker([coords[1], coords[0]]).bindPopup(name);
markers.addLayer(marker);

But instead, you're re-binding a popup to the entire marker cluster group each time, e.g.:

var marker = L.marker([coords[1], coords[0]]);
markers.addLayer(marker).bindPopup(name);

If you find it difficult to understand how that applies to your code, think about the difference between:

markers.addLayer(marker.bindPopup(/* stuff */));

and

markers.addLayer(marker).bindPopup(/* stuff */);

Remember that, in Leaflet, markers.addLayer() returns a reference to the marker cluster group itself (which enables method cascading), so the .bindPopup() method running is that of the cluster group, not that of any individual marker.

| improve this answer | |
  • Thank you, Ivan! That's a really straightforward explanation. I just moved .bindPopup to inside the parentheses and it worked perfectly. – Chris L Sep 11 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.