简体   繁体   中英

Uncaught (in promise) TypeError: Cannot read property '0' of undefined. Pulling from a csv file to populate an array

I am using the Leafleft Map API and a csv file to place markers on an interactive map (like an embedded google map) and I want to be able to click on a marker so that it changes the contents of a div tag (here with the id of infoName)on the website.

I get an error from the last line of code saying "Cannot read property '0' of undefined" and I think it has to do with promises and data fetching and maybe scope. Here is my code:

var restaurants = [];

makeMarkers();

async function getData() {
  const response = await fetch('restaurantData.csv');
  const data = await response.text();

  const rows = data.split(/\n/).slice(1);
  rows.pop();
  for (var i = 0; i < rows.length; i++) {
    const col = rows[i].split(',');
    restaurants[i] = col;
  }
}

async function makeMarkers() {
  await getData();
  for (var j = 0; j < restaurants.length; j++) {
    L.marker([restaurants[j][7], restaurants[j][8]]).addTo(mymap).on('click', async function () {
            document.getElementById('infoName').textContent = await restaurants[j][0].toString();
          });
  }
}

Any help is much appreciated!

Probably a scoping issue. var is hoisted, so restaurants[j] is actually using j after it has been incremented to restaurants.length.
Removed async because it is unnecessary there.

  for (var j = 0; j < restaurants.length; j++) {
    let k = j;
    L.marker([restaurants[k][7], restaurants[k][8]]).addTo(mymap).on('click', function () {
            document.getElementById('infoName').textContent = restaurants[k][0].toString();
          });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM