How can I get Leaflet markerClusters to work with reading data from CSV with PapaParse?

242 Views Asked by At

I am trying to combine directions from two Leaflet tutorials:

  1. Getting marker data from CSV using PapaParse: https://github.com/HandsOnDataViz/leaflet-map-csv
  2. Clustering tutorial: https://asmaloney.com/2015/06/code/clustering-markers-on-leaflet-maps/

and here is what I have:

//create cluster group
var markerClusters = L.markerClusterGroup();

// Read markers data from data.csv
$.get('./data_jittered.csv', function(csvString) {
  
// Use PapaParse to convert string to array of objects
var data = Papa.parse(csvString, {header: true, dynamicTyping: true}).data;
// For each row in data, create a marker and add it to the map
// For each row, columns `Latitude`, `Longitude`, and `Title` are required
for (var i in data) {
  var row = data[i];

  var marker = L.marker([row.New_Lat, row.New_Long], {
    opacity: 1
  }).bindPopup(row.Title);      
  marker.addTo(map);
  markerClusters.addLayer(marker);
 
}
map.addLayer(markerClusters);

Currently, the markers are loading but the clustering function is not working: https://maggiehm.github.io/nzamorawilson-map/

1

There are 1 best solutions below

0
On
marker.addTo(map);

was the issue. I followed the example provided by Dom in the comments here: stackoverflow.com/a/66616249/10684798

and updated the code (with simplified variables) to:

var markers = L.markerClusterGroup();

$.get('./data_jittered.csv', function(csvString) {
  
var data = Papa.parse(csvString, {header: true, dynamicTyping: true}).data;
for (var i in data) {
  var row = data[i];
  var marker = L.marker([row.New_Lat, row.New_Long], {
      opacity: 1
  }).bindPopup(row.Title);      
  markers.addLayer(marker);
}
});
map.addLayer(markers)

The clustering function works now: https://maggiehm.github.io/nzamorawilson-map/