Search code examples
javascriptchartsvisualizationgauge

Google visualization gauge : Cannot read property 'arrayToDataTable' of undefined


I'm working on JS and specially on google visualization gauge. I try to integrate this chart into my script.

But I've got this error :

Uncaught TypeError: Cannot read property 'arrayToDataTable' of undefined
    at drawChart (main.js:59)
    at main (main.js:10)
    at main.js:4

This is my code :

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

    main();

    function main(){
        var valueGauge=requestHttp("https://raptorjesus.000webhostapp.com/lecture.php");
        drawChart(valueGauge);
        editElementHTML("valeurExacte","La quantité de CO2 est de : ",valueGauge," ppm.");

        [...]

        setTimeout(main, 1000); //On dit à JS que la fonction main a une durée de vie de 1 seconde
    }

    function requestHttp(url){

[...]

    }

    function drawChart(valueGauge) {


       var data = google.visualization.arrayToDataTable([
            ['Label', 'Value'],
            ['CO2', valueGauge] //on remplace la valeur stricte du snippet google par la variable de la requête

        ]);

        var options = {
            width: 350, height: 250,
            redFrom: 5000, redTo: 6000,
            yellowFrom: 1700, yellowTo: 5000,
            greenFrom: 1000, greenTo: 1700,
            minorTicks: 5,
            max: 6000,
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

        chart.draw(data, options);
    }

    function editElementHTML(idElem, text1, text2, variable){
        var Element= (document.getElementById(idElem));
        Element.innerHTML = text1+ variable+text2;
    }

The error come from line var data = google.visualization.arrayToDataTable but I don't know why because I don't see any error of syntax and it's just the same code as Google chart Documentation...

Any ideas?


Solution

  • Solved : I had to use google.charts.setOnLoadCallback(drawChart) instead of drawchart()