TransWikia.com

Popup marker info problems in Leaflet when using markercluster

Geographic Information Systems Asked on January 6, 2021

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?

One Answer

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.

Correct answer by IvanSanchez on January 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP