Google Charts Not Loading on Intellij

2019-09-14 08:44发布

问题:

I am trying to make a pie chart with Google Charts. When I put this code into an html file and run it on its own it works fine.

This is what it looks like:

However, when I run it within my project in Intellij nothing appears.

Here is my code:

<div>

        <!--Load the AJAX API-->
        <!--script type="text/javascript" src="views/jsapi.js"></script-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script type="text/javascript">
console.log("1");
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.1', {'packages':['corechart']});
console.log("2");

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
console.log("3");

    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {
        console.log("4");

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
            ['Mushrooms', 3],
            ['Onions', 1],
            ['Olives', 1],
            ['Zucchini', 1],
            ['Pepperoni', 2]
        ]);
        console.log("5");

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
            'width':400,
            'height':300};

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
        console.log("6");

    }
console.log("7");

</script>
    <!--Div that will hold the pie chart-->
    <div id="content">
        <div id="chart_div"></div>
    </div>
</div>

Why is this happening?

回答1:

I got it to work by modifying this line of code:

    google.load('visualization', '1', {packages: ['corechart']});

To this:

    google.load('visualization', '1', {packages: ['corechart'], callback : drawChart});

See Zanona's answer here for further explanation: google.load causes empty dom/screen