我想使用椭圆进行世界人口数据可视化,但我的代码不起作用,椭圆不显示。我的代码有什么问题吗? 我确信 json 文件的内容没有任何问题。我不确定我的 for 循环,但我无法检测到这段代码中的错误是什么
let popu;
let latlon;
const mappa = new Mappa("Leaflet");
let trainMap;
let canvas;
let data = [];
const options = {
lat: 0,
lng: 0,
zoom: 1.5,
style: "http://{s}.tile.osm.org/{z}/{x}/{y}.png",
};
function preload() {
popu = loadJSON("vn.json");
latlon = loadJSON("latlon.json");
}
function setup() {
canvas = createCanvas(800, 600);
trainMap = mappa.tileMap(options);
trainMap.overlay(canvas);
let maxSubs = 0;
let minSubs = Infinity;
for (let i = 0; i < popu.length; i++) {
let country = popu[i].country;
let address = latlon[country];
if (address) {
let lat = address[0];
let lon = address[1];
let count = Number(popu[i].population);
data.push({
lat,
lon,
count,
});
if (count > maxSubs) {
maxSubs = count;
}
if (count < minSubs) {
minSubs = count;
}
}
}
let minD = sqrt(minSubs);
let maxD = sqrt(maxSubs);
for (let coun of data) {
coun.diameter = map(sqrt(coun.count), minD, maxD, 1, 20);
}
}
function draw() {
clear();
for (let coun of data) {
const pix = trainMap.latLngToPixel(coun.lat, coun.lon);
fill(frameCount % 255, 0, 200, 100);
const zoom = trainMap.zoom();
const scl = pow(2, zoom);
ellipse(pix.x, pix.y, coun.diameter * scl);
}
}
这是我的 json 文件的一部分 vn.json
[
{
"country": "Afghanistan",
"population": 37172386
},
{
"country": "Albania",
"population": 2866376
},
{
"country": "Algeria",
"population": 42228429
},
{
"country": "American Samoa",
"population": 55465
},
{
"country": "Andorra",
"population": 77006
}
]
latlon.json
{
"ad": [
"42.5000",
"1.5000"
],
"ae": [
"24.0000",
"54.0000"
],
"af": [
"33.0000",
"65.0000"
],
"ag": [
"17.0500",
"-61.8000"
],
"ai": [
"18.2500",
"-63.1667"
]
}
我想让代表人口的椭圆能够显示出来
首先在设置中,您需要将
popu.length
更改为 Object.keys(popu).length
。长度没有正确获取,因此数据也没有正确生成。
第二件事是您尝试使用国家/地区的全名作为密钥从
latlon.json
文件中获取地址。问题是,vn.json
中的国家键只有2个字母,而latlon.json
中的国家名称是全名。您需要更改其中一个文件中的名称才能使其在这种情况下工作,或者找到任何其他方法将 pupu
与 latlon
数组相匹配。
let country = popu[i].country; // the name is 2 letters code, 'af' for example
let address = latlon[country]; // the keys in latlon are full names, so 'af' won't get any value from the array.
我将
vn.json
中的国家/地区参数更改为国家/地区的全名,并且可视化工作正常。