First off, the first row of your csv must be a comma separated list of column names to use this method. If this is not possible, add a comment about this and I will see if I can work out how to use d3.csv.parseRows
instead of d3.csv.parse
. d3.csv.parse
is called by the assessor function on .defer(function, url, assessor)
.
I am going to assume your file now looks like this:
danger.csv
iso,level
AFG,100
ALB,0
DZA,12
...
Using this, you can create a lookup hash from ISO3 to danger level.
var dangerByISO3 = d3.map();
queue()
.defer(d3.json, "url to topo.json")
.defer(d3.csv, "url to danger.csv", function(d) {dangerByISO3.set(d.iso, +d.level);})
.await(ready);
function ready(error, world) {
//You now have world as your available topojson
//And you have dangerByISO3 as your danger level hash
//You can lookup a danger level by dangerByISO3.get(ISO3 code)
}
Code walkthrough
var dangerByISO3 = d3.map();
First you create a d3.map() object which will function as your key hash, and store this in the variable dangerByISO3.
queue()
Use queue for parallel loading.
.defer(d3.json, "url to topo.json")
Load your topojson as the first argument to be passed to the await function (after error). Note the style here where this is a chained function on queue()
, but listed on a separate line (there is no terminating semicolon on queue()
).
.defer(d3.csv, "url to danger.csv", function(d) {dangerByISO3.set(d.iso, +d.level);})
Two things are happening here. First, you are loading danger.csv as your second argument to be passed to the await function. As you will see below, this argument is not actually used. Instead, an assessor argument is provided to the loading function, d3.csv. This assessor will process each row of the csv. In this case, we call the set function on dangerByISO3 so that for each combination of an iso
key, we set the level
as the value to go with that key. The +d.level
notation uses unary +
to coerce the value of d.level to a number.
.await(ready);
Once both data sources are loaded, they are passed as two separate arguments to the function ready()
. The first argument to the callback is always the first error that occurred. If no error occurred, then null will be passed as the first argument. The second argument is the first data source (result of the first task), and the third argument is the second data source (result of the second task).
function ready(error, world) {...}
This is the callback function ready()
. First we take the error
argument which should be null if the two loading tasks completed successfully (you should actually add language to catch and handle errors). Next we take the topojson data as the object countries
. This data should be processed in the body of the function with something like .data(topojson.feature(world,world.objects.countries).features)
. Since ready()
does not take a third argument, the result of the second task, our csv, is simply discarded. We only used it to build the key hash and did not need it after that.