How can I loop a csv file with countries and data in Google Geochart?

I have a large csv file that contains the country and the corresponding piece of data for that country.
In a form (excel example):

[Country1, Data1],
[Country2, Data2] etc

      

How to use a loop with a csv file to create each item in a Geocharts array. Instead of writing everything like in the example below.

 function drawRegionsMap() {

    var data = google.visualization.arrayToDataTable([
      ['Country', 'Popularity'],
      ['Germany', 200],
      ['United States', 300],
      ['Brazil', 400],
      ['Canada', 500],
      ['France', 600],
      ['RU', 700]
    ]);

      

I'm not sure how to work with the csv file as I haven't worked with them in js before, however I stumbled upon the jquery-csv tool at https://github.com/evanplaice/jquery-csv but I don't quite understand it completely ...

+3


source to share


1 answer


Your CSV file is already mostly correct for what you need. When you load the CSV into javascript, use the parsing function castToScalar

to make sure your numbers are parsed appropriately, then add the data to your DataTable. If your CSV contains a header row with column labels, you can simply add it like your example:

var rawData = $.csv.toArrays(csv, {
    onParseValue: $.csv.hooks.castToScalar
});
var data = google.visualization.arrayToDataTable(rawData);

      



If your CSV contains no headers, you need to do some tweaks first:

var rawData = $.csv.toArrays(csv, {
    onParseValue: $.csv.hooks.castToScalar
});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Value');
data.addRows(rawData);

      

+2


source







All Articles