TransWikia.com

Using my "layerGroup" outside of the function

Geographic Information Systems Asked by SM21 on January 28, 2021

The console show this error: "spots is not defined"
How can I use my layerGroup spots outside of the function?

$.get("./data.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.Latitude, row.Longitude], {
      opacity: 1,
    }).bindPopup(row.Name);

    var spots = L.layerGroup([marker]);
  }
});

var overlaySpots = {
  "Some name": spots,
};

L.control.layers(null, overlaySpots).addTo(map);

spots.addTo(map);

One Answer

Define the layergroup outside and then add the marker:

var spots = L.layerGroup();

$.get("./data.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.Latitude, row.Longitude], {
      opacity: 1,
    }).bindPopup(row.Name);

    spots.addLayer(marker);
  }
});

var overlaySpots = {
  "Some name": spots,
};

L.control.layers(null, overlaySpots).addTo(map);

spots.addTo(map);

Correct answer by Falke Design on January 28, 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