1

I am working on a web app that loads JSON files into leaflet layers when an action happens. The following code works with the "let" statement but if it's taken out the last loop variables override each layer.

for (var i = 0; i < area_labels.length; i++) {

    let label = area_labels[i];
    let label_color = String(getColor(label));
    let label_name = getReadableName(label);

    $.getJSON(`static/shapefiles/FCN_Smoothed/geojson_class_${label}.json`, function(data) {
      layer = L.geoJSON(data, {style:{color:`${label_color}`, stroke:false, fillOpacity:0.6}})
      lc.addOverlay(layer, label_name);
    });
}

area_labels is passed to the function above from a $.ajax function which can be seen as such:

$.ajax({
    url: '/get_target_area',
    type: 'POST',
    dataType:"json",
    data:  JSON.stringify(payload),

    success: function(data) {
    ...do stuff...
    area_labels = data[5];
    loadLeafletLayers(area_labels);
    }
});

Is there a way to make this work without using the "let" statement?

Barrera
  • 57
  • 1
  • 7

1 Answers1

1

For this to work without using let (which I presume you need in order to support < IE11) you will need to use a closure within the for loop in order to maintain the scope of the variables:

for (var i = 0; i < area_labels.length; i++) {
  (function(l, l_col, l_name) {
    $.getJSON('static/shapefiles/FCN_Smoothed/geojson_class_' + l + '.json', function(data) {
      layer = L.geoJSON(data, {
        style: {
          color: l_col,
          stroke: false,
          fillOpacity: 0.6
        }
      })
      lc.addOverlay(l, l_name);
    });
  })(area_labels[i], String(getColor(label)), getReadableName(label));
}

Note I also removed the template literals as if you need to remove the let keyword for browser compatibility then that certainly isn't going to work either.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339