Values in array read in from d3.csv are undefined outside of function despite global variable declaration

huangapple go评论82阅读模式
英文:

Values in array read in from d3.csv are undefined outside of function despite global variable declaration

问题

谢谢你提前的帮助!
我在我的代码中全局声明了四个数组。然后,在从CSV读取数据的函数中,我将数据值分配给数组元素。然而,在这个函数之外,数组元素是未定义的,我似乎找不到问题所在...
我正在使用d3版本7(<script src="http://d3js.org/d3.v7.min.js" charset="utf-8"></script>)和Google Maps JavaScript API。

我的CSV文件格式为Project_Name、Artist、Lat、Long - 大约有300个值。

// 请求所需的库。
const { Map, InfoWindow } = await google.maps.importLibrary(&quot;maps&quot;);
const { LatLng } = await google.maps.importLibrary(&quot;core&quot;);
const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(&quot;marker&quot;);

// 全局变量
let map;
let projectName = [];
let artist = [];
let lat = [];
let long = [];
let markers = [];


async function data() {
  d3.csv(&quot;/data/single.csv&quot;, function(d) {
    return {
      projectName: +d.Project_Name,
      artist: +d.Artist,
      lat: +d.Latitude,
      long: +d.Longitude,
    }
  }).then(function(d) {
    for (var i = 0; i &lt; d.length; i++) {
      projectName[i] = d[i].Project_Name;
      artist[i] = d[i].Artist;
      lat[i] = parseFloat(d[i].Latitude);
      long[i] = parseFloat(d[i].Longitude);
    }
  });
}



function createMarkers(m){
  for (var z=0; z &lt; lat.length; z++) {
    markers[z] = new google.maps.Marker({
      position: new google.maps.LatLng(lat[z], long[z]),
      map: m,
      title: projectName[z],
    });
  } 
}

async function initMap() {
  
  const map = new Map(document.getElementById(&quot;map&quot;), {
    zoom: 11,
    center: { lat: 37.4239163, lng: -122.0947209 },
    mapId: &quot;[MAP ID]&quot;,
    mapTypeControl: false,
  });
  const infoWindow = new google.maps.InfoWindow({
    content: &quot;&quot;,
    disableAutoPan: true,
  });
  
  // 读取CSV文件
  data();
  
  // 标记
  createMarkers(map);
  
}

initMap();

我尝试使用await,但这没有解决问题。还尝试使用setTimeout,但结果是NaN的值,而不是未定义的值。

英文:

Thank you in advance for your help!
I have declared four arrays globally in my code. Then, in the function to read the data from the csv, I assign the data values to array elements. However, the array elements are undefined outside of this function, and I can't seem to find the issue...
I am using d3 version 7 (<script src="http://d3js.org/d3.v7.min.js" charset="utf-8"></script>) and Google Maps Javascript API.

My CSV file is formatted Project_Name, Artist, Lat, Long - with around 300 values.

// Request needed libraries.
const { Map, InfoWindow } = await google.maps.importLibrary(&quot;maps&quot;);
const { LatLng } = await google.maps.importLibrary(&quot;core&quot;);
const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(&quot;marker&quot;);
//Global Vars
let map;
let projectName = [];
let artist = [];
let lat = [];
let long = [];
let markers = [];
async function data() {
d3.csv(&quot;/data/single.csv&quot;, function(d) {
return {
projectName: +d.Project_Name,
artist: +d.Artist,
lat: +d.Latitude,
long: +d.Longitude,
}
}).then(function(d) {
for (var i = 0; i &lt; d.length; i++) {
projectName[i] = d[i].Project_Name;
artist[i] = d[i].Artist;
lat[i] = parseFloat(d[i].Latitude);
long[i] = parseFloat(d[i].Longitude);
}
});
}
function createMarkers(m){
for (var z=0; z &lt; lat.length; z++) {
markers[z] = new google.maps.Marker({
position: new google.maps.LatLng(lat[z], long[z]),
map: m,
title: projectName[z],
});
} 
}
async function initMap() {
const map = new Map(document.getElementById(&quot;map&quot;), {
zoom: 11,
center: { lat: 37.4239163, lng: -122.0947209 },
mapId: &quot;[MAP ID]&quot;,
mapTypeControl: false,
});
const infoWindow = new google.maps.InfoWindow({
content: &quot;&quot;,
disableAutoPan: true,
});
//READ CSV FILE
data();
//MARKERS
createMarkers(map);
}
initMap();

I tried using await, that didn't solve the problem. Also tried to use setTimeout, which resulted in the value of NaN instead of undefined.

答案1

得分: 0

代码部分不要翻译,只返回翻译好的内容:

正在发生的情况是d3.csv是异步的。你有一个正确的想法,希望在某处使用await,但你必须等待d3.csv的承诺。
如果你想要"等待"数据填充,你必须返回d3.csv的承诺:

async function data() {
  return d3.csv("/data/single.csv", function(d) {
   // ...
  });
}

然后在调用createMarkers();之前等待数据函数:

... 
    // 读取CSV文件
    await data();
    // 现在你的全局数组应该已经填充了
    createMarkers();
...
英文:

What's happening is that d3.csv is asynchronous. You got the right idea by wanting to await somewhere, but you have to await the d3.csv promise.
If you want to "await" data to be filled, you have to return d3.csv promise :

async function data() {
return d3.csv(&quot;/data/single.csv&quot;, function(d) {
...
});
}

Then await the data function before calling createMarkers(); :

... 
//READ CSV FILE
await data();
// now your global arrays should be filled
createMarkers();
...

huangapple
  • 本文由 发表于 2023年7月18日 12:34:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76709561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定