eoin
eoin

Reputation: 329

How do I parse a JSON file to bind data to a d3 choropleth map

I'm trying to take data in from a JSON file and link it to my geoJSON file to create a choropleth map with the county colours bound to the "amount" value but also I would like a corresponding "comment" value to be bound to a div for when I mouseover that county.

My code at http://bl.ocks.org/eoiny/6244102 will work to generate a choropleth map when my counties.json data is in the form:

"Carlow":3,"Cavan":4,"Clare":5,"Cork":3,

But things get tricky when I try to use the following form:

{
"id":"Carlow",
"amount":11,
"comment":"The figures for Carlow show a something." },

I can't get my head around how join the "id": "Carlow" from counties.json and "id": "Carlow" path created from ireland.json, while at the same time to have access to the other values in counties.json i.e. "amount" and "comment".

Apologies for my inarticulate question but if anyone could point me to an example or reference I could look up that would be great.

Upvotes: 0

Views: 813

Answers (1)

Ray Waldin
Ray Waldin

Reputation: 3227

I would preprocess the data when it's loaded to make lookup easier in your quantize function. Basically, replace this: data = json; with this:

data = json.reduce(function(result, county) {
    result[county.id] = county;
    return result;
}, {});

and then in your quantize function, you get at the amounts like this:

function quantize(d) {
    return "q" + Math.min(8, ~~(data[d.id].amount * 9 / 12)) + "-9";
}

What the preprocessing does is turn this array (easily accessed by index):

[{id: 'xyz', ...}, {id: 'pdq', ...}, ...]

into this object with county keys (easily accessed by county id):

{'xyz': {id: 'xyz', ...}, 'pdq': {id: 'pdq', ...}, ...}

Here's the working gist: http://bl.ocks.org/rwaldin/6244803

Upvotes: 1

Related Questions