SuzukiBlue
SuzukiBlue

Reputation: 135

D3 Map - feeding data to tootip

I am trying to adapt to my needs this very neat example based on this dataset.

Instead of randomly generated data:

           var low=Math.round(100*Math.random()), 
           mid=Math.round(100*Math.random()), 
           high=Math.round(100*Math.random());`

I would like to display some of the properties e.g. real population or area of the state. I was trying to add properties to each line in uStates.js

{id:"OH",n:"Ohio", pop:"11.59", area:"116,096", d:"M735.32497,(..),193.32832Z"},

and plug it to tooltipHTML function

           function tooltipHtml(n, d, pop, area)
           return "<h4>"+n+"</h4><table>"+
           "<tr><td> Population </td><td>"+pop+"</td></tr>"+
           "<tr><td> Area </td><td>"+area+"</td></tr>"+
           "</table>";

but it doesn't work (in place of a value an undefined appears).

My native software is R. I did not find a suitable solution there thus I am trying my luck with Javascript to which I know very little. Thanks in advance for help.

Upvotes: 0

Views: 57

Answers (1)

tarulen
tarulen

Reputation: 2100

In order to use uStates.js seamlessly, your own data should be separated from the path coordinates (in short: do not edit uStates.js).

The format for your data should be:

 var data={
     "OH": {pop:"11.59", area:"116,096", color:"#FFF"},
     "NY": { ... },
     ...
    };

The color field is mandatory for uStates to work. You can make it fit your other values automatically, and you can also convert your data to this format if you have it in another way (but this is not the scope of this answer, don't hesitate to ask for more about this).

Then, you only need to edit the tooltipHTML function to take the pop and area fields of your data (d):

    function tooltipHtml(n, d) {
       return "<h4>"+n+"</h4><table>"+
       "<tr><td>Low Low Low</td><td>"+d.pop+"</td></tr>"+
       "<tr><td>Average Average</td><td>"+d.area+"</td></tr>"+
       "</table>";
    }

Finally, call uStates with

  uStates.draw("#statesvg", data, tooltipHtml);

Upvotes: 1

Related Questions