在d3中的csv和json之间链接相同的变量

时间:2019-03-05 18:52:17

标签: javascript json csv d3.js svg

我当前要使用d3制作世界地图。

我正在使用https://unpkg.com/world-atlas@1.1.4/world/50m.json加载数据以绘制世界地图,其中变量id与我的dataset2010.csvCountry_code相同。

如何通过json的id和csv的Country_code链接这两个文件。

以下是我的main.js

(function (d3,topojson) {
  'use strict';

  const svg = d3.select('svg');

  const projection = d3.geoNaturalEarth1();
  const pathGenerator = d3.geoPath().projection(projection);

  const g = svg.append('g');

  g.append('path')
      .attr('class', 'sphere')
      .attr('d', pathGenerator({type: 'Sphere'}));

  svg.call(d3.zoom().on('zoom', () => {
    g.attr('transform', d3.event.transform);
  }));

  Promise.all([
    d3.json('https://unpkg.com/world-atlas@1.1.4/world/50m.json'),
    d3.csv('dataset2010.csv')
  ]).then(([topoJSONdata, csvData]) => {


    // here I could not link them
    const countryName = {};
    csvData.forEach(d => {
      countryName[d.Country_code] = d.name;
      console.log(d.Country_code);
      console.log(d.name);
    });



    const countries = topojson.feature(topoJSONdata, topoJSONdata.objects.countries);
    g.selectAll('path').data(countries.features)
      .enter().append('path')
        .attr('class', 'country')
        .attr('d', pathGenerator)
      .append('title')
        .text(d => countryName[d.id]); //the d.id is from the json file.

  });

}(d3,topojson));

0 个答案:

没有答案