因此,我尝试使用一个 API 中的数据(特别是一个国家/地区的 iso3 代码)从另一个 API 加载其 LatLong,然后在 map 上绘制。
我遇到的问题是,我将 preload() 中的第一个 API(自然灾害位置)加载到一个数组中,然后我无法访问该数组内的信息来获取列出的所有灾难的 iso3,除非我访问它来自draw()。
问题是,当我将经纬度数据加载到 map 中时,它显示为未定义,但是当我从 preload() 加载经纬度数据时,灾难数据是未定义的。
这段代码一直有效,直到调用 mapM() 并尝试从临时数组中加载经纬度值,因为它们返回时未定义,无论我在哪里这些 GET 查询始终是未定义的。
非常感谢任何帮助,我对 JS 很陌生,所以放轻松!
最佳答案
此类问题的最佳答案通常是通读 the reference :
This method is asynchronous, meaning it may not finish before the next line in your sketch is executed.
这意味着您的 temp[i] = loadJSON(urlC);
线路在 console.log(temp);
之前但未完成行执行。
这是因为loadJSON()
函数是异步的,这意味着它在后台运行,而不是在主线程上运行。这通常很有用,因为您不希望每次发出新请求时代码都卡住,但它也会导致像您这样的错误。
要解决此问题,您可以向 loadJSON()
添加回调函数线。再次,来自引用:
function setup() {
noLoop();
var url =
'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +
'summary/all_day.geojson';
loadJSON(url, drawEarthquake);
}
function draw() {
background(200);
}
function drawEarthquake(earthquakes) {
// Get the magnitude and name of the earthquake out of the loaded JSON
var earthquakeMag = earthquakes.features[0].properties.mag;
var earthquakeName = earthquakes.features[0].properties.place;
ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);
textAlign(CENTER);
text(earthquakeName, 0, height - 30, width, 30);
}
请注意 drawEarthquake()
函数被传递到 loadJSON()
功能。当 loadJSON()
函数完成后,会调用 drawEarthequake()
自动运行。
您可能想做类似的事情。
关于javascript - 加载另一个API的数据的1个API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832136/