Cara menggunakan GOOGLECHART pada JavaScript

Bagan atau chart memang mempunyai fungsi yang cukup penting dalam dunia statistik maupun analisis. Dengan ditampilkannya bagan maka representasi data akan terlihat secara jelas dan memungkinkan data menjadi mudah dibaca. Berkaitan dengan bagan, seorang web developer sebenarnya bisa membuatnya dengan native PHP language. Namun hasil yang ditampilkan pasti terlihat kaku dan kurang interaktif.

Cara menggunakan GOOGLECHART pada JavaScript

PHP JSON Google Chart

Bagi sebagian developer web, menampilkan bagan dengan memanfaatkan library chart akan mempunyai banyak kelebihan. Dari sisi estetika desain terlihat baik, dan interaksi data pun dapat terlihat teratur. Di internet terdapat banyak sekali library sejenis ini, namun tutorial pada artikel ini akan menjelaskan bagaimana caranya membuat bagan grafik yang dinamis menggunakan API dari Google, yakni Google Chart Tools.

Tutorial

Download Source Code

Mari kita mulai saja dengan studi kasus pembuatan bagan “Hasil Kuesioner” dengan 5 parameter “Sangat Tidak Puas“, “Tidak Puas“, “Puas“, “Cukup Puas“, dan “Sangat Puas“. Pada 5 parameter tersebut akan terdapat nilai-nilai hasil kounter (perhitungan) dari pengisian kuesioner. Ibaratkan pada setiap parameter sudah terisi beberapa nilai. Mari kita coba membuatnya:

Pertama, kita harus membuat database menggunakan MySQL, bernama “Kuesioner” atau terserah, buat juga tabel di dalamnya dengan nama “Hasil“, pada tabel hasil tersebut buat 2 field dengan nama “Parameter” (String) dan “Nilai” (Integer). Isikan masing-masing parameter dan nilai sebagai dummy datanya, seperti berikut :

Cara menggunakan GOOGLECHART pada JavaScript

Parameter dan Nilai Dummy Pada Kuesioner

Perlu diingat parameter dan nilai tersebut kita isikan secara manual melalui phpmyadmin. Nilai pada parameter merupakan dummy yang bisa kita ubah sesuai keinginan pembaca.

Kemudian Buka folder xampp localhost Anda, dan buat folder baru bernama “Googlechart” (optional). Di dalamnya buat dua file bernama index.php dan json.php. Javascript yang diperlukan untuk mendukung pembuatan chart ini adalah API dari Google Chart dan Jquery Berikut adalah isi dari file index.php :

file index.php di atas adalah memanggil hasil query database “kuesioner” berbentuk JSON (Notasi Objek Javascript) yang nanti akan kita buat. Berikut adalah isi dari file json.php :

Hasil dari query di atas akan terbentuk data Json yang akan dapat terbaca oleh Google Chart. Anda bisa melihat hasil data json dengan mengetikkan localhost/googlechart/json.php. Dan untuk melihat hasil tampilan Bagan chart yang terbentuk kita tinggal memanggil melalui url localhost/googlechart/index.php. Hasil chart akan tampil seperti di bawah ini :

Cara menggunakan GOOGLECHART pada JavaScript

Hasil Google Chart Tool Untuk Kuesioner

Untuk lebih memahaminya, saya sudah menyertakan link source code yang telah saya upload ke Github.

  • Home
  • Guides
  • Reference
  • Support

Stay organized with collections Save and categorize content based on your preferences.

What we've covered so far is sufficient for many web pages: you've drawn your chart on the page. However, if you want to catch user clicks, or need to manipulate properties or data in a chart that you've already drawn, you need to listen for events thrown by the chart.

All charts throw some kinds of events. Here are the most common:

  • ready - Thrown when the chart is drawn on the page and ready to respond to methods. Listen for this event if you need to request information from the chart.
  • select - Thrown when the user selects something on the chart: typically by clicking on a bar or pie slice.
  • error - Thrown when the chart can't render the data passed in, typically because the DataTable format is wrong.
  • onmouseover and onmouseout - Thrown when the user mouses over or off of a specific chart element, respectively.

Listening for events is simple; simply call google.visualization.events.addListener() passing in a handle to the chart, the name of the event to catch, and the name of a handler to call when the event is thrown. You can call this method with any chart handle, even if you haven't called draw() yet. Note that you can call google.visualization.events.addOneTimeListener() if you want the listener to be called exactly once before removing itself.

Here's a partial code snippet showing how to register to catch a chart's select event:

load libraries...

function drawChart() {

  prepare data...

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

  // The select handler. Call the chart's getSelection() method
  function selectHandler() {
    var selectedItem = chart.getSelection()[0];
    if (selectedItem) {
      var value = data.getValue(selectedItem.row, selectedItem.column);
      alert('The user selected ' + value);
    }
  }

  // Listen for the 'select' event, and call my function selectHandler() when
  // the user selects something on the chart.
  google.visualization.events.addListener(chart, 'select', selectHandler);

  draw the chart...

}

The following shows the Hello Charts code example with a new select event listener. Try it out yourself.

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

      // Load the Visualization API and the piechart package.
      google.charts.load('current', {'packages':['corechart']});

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

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

        // 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]
        ]);

        // 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'));

        function selectHandler() {
          var selectedItem = chart.getSelection()[0];
          if (selectedItem) {
            var topping = data.getValue(selectedItem.row, 0);
            alert('The user selected ' + topping);
          }
        }

        google.visualization.events.addListener(chart, 'select', selectHandler);    
        chart.draw(data, options);
      }

    </script>
  </head>
  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div" style="width:400; height:300"></div>
  </body>
</html>

More Information

  • Handling Events
  • Controls and Dashboards
  • getSelection()
  • google.visualization.events.addListener()

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2016-01-22 UTC.

[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]