Search code examples
csvchartsgoogle-visualization

Drawing a Google Visualization Chart from .CSV file


I'm not a programmer

I want to Draw a Google Visualization Chart from .CSV file

I have .csv file as below:

time,temperature
2023-08-21 12:00:00,25
2023-08-21 12:01:00,26
2023-08-21 12:02:00,27

and this is the my code :

<!DOCTYPE html><html><head><title>Temperature vs. Time Chart</title><script src="https://www.google.com/jsapi"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.csv/0.71/jquery.csv.min.js"></script></head><body><div id="chart"></div>
<script>// Load the Google Visualization API and the jQuery-CSV library.google.load("visualization", "1", {packages: ["corechart", "controls"]});$.getScript("https://cdnjs.cloudflare.com/ajax/libs/jquery.csv/0.71/jquery.csv.min.js");
// Function to draw the chart.
function drawChart() {
  // Get the data from the CSV file.
  var csvData = $.csv("temp.csv");

  // Create a new DataTable object from the CSV data.
  var data = new google.visualization.arrayToDataTable(csvData);

  // Create a new chart object.
  var chart = new google.visualization.LineChart(document.getElementById("chart"));

  // Set the chart options.
  chart.options.title = "Temperature vs. Time";
  chart.options.width = 600;
  chart.options.height = 400;

  // Draw the chart.
  chart.draw(data);
}

// Call the drawChart() function when the page loads.
google.setOnLoadCallback(drawChart);
</script></body></html>

unfortunately not working giving me a blank page


Solution

  • first, need to make sure you're calling google's load statement, didn't see it in the code provided.

    google.charts.load('current', {packages: ['corechart']});
    

    and you can use the promise the load statement returns to know when the page has loaded.

    next, options should be a separate variable, and passed as the second argument to the draw method.

    see following snippet...

    google.charts.load('current', {
      packages: ['corechart']
    }).then(function () {
      // Get the data from the CSV file.
      var csvData = $.csv("temp.csv");
    
      // Create a new DataTable object from the CSV data.
      var data = new google.visualization.arrayToDataTable(csvData);
    
      // Create a new chart object.
      var chart = new google.visualization.LineChart(document.getElementById("chart"));
    
      // Set the chart options.
      var options = {};
      options.title = "Temperature vs. Time";
      options.width = 600;
      options.height = 400;
    
      // Draw the chart.
      chart.draw(data, options);
    });
    

    EDIT

    and just noticed...

    you need to use the following url to load google charts.

    <script src="https://www.gstatic.com/charts/loader.js"></script>
    

    jsapi has been deprecated...

    see update library loader code