Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Cách thêm Google Charts vào trang web

Giới thiệu

Google Charts là thư viện JavaScript miễn phí, mạnh mẽ để vẽ biểu đồ tương tác (biểu đồ cột, tròn, đường, tổ hợp...). Dữ liệu có thể hardcode, từ Google Sheets, hoặc API backend.

Các bước tích hợp cơ bản

  1. Nhúng loader: <script src="https://www.gstatic.com/charts/loader.js"></script>
  2. Load package: google.charts.load('current', {packages: ['corechart']});
  3. Set callback: google.charts.setOnLoadCallback(drawChart);
  4. Vẽ chart trong function drawChart().

Ví dụ hoàn chỉnh: Biểu đồ cột (Bar Chart)

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Google Charts - Bar Chart</title>
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
        google.charts.load('current', { packages: ['corechart'] });
        google.charts.setOnLoadCallback(drawChart);
        
        function drawChart() {
            // 1. Dữ liệu (DataTable)
            var data = google.visualization.arrayToDataTable([
                ['Năm', 'Số người biết chữ (triệu)'],
                ['2013', 500],
                ['2014', 800],
                ['2015', 1000],
                ['2016', 1200],
                ['2017', 1400]
            ]);
            
            // 2. Tùy chọn (Options)
            var options = {
                title: 'Tỷ lệ biết chữ tại Việt Nam (2013-2017)',
                titleTextStyle: { fontSize: 18, bold: true, color: '#333' },
                width: '100%',          // Responsive width
                height: 400,
                chartArea: { width: '70%', height: '65%' },
                legend: { position: 'none' },
                colors: ['#8e24aa'],
                backgroundColor: 'transparent',
                hAxis: { title: 'Năm', textStyle: { fontSize: 12 } },
                vAxis: { 
                    title: 'Triệu người', 
                    minValue: 0,
                    gridlines: { color: '#f0f0f0' }
                },
                animation: { duration: 1000, easing: 'out', startup: true },
                tooltip: { isHtml: true }
            };
            
            // 3. Khởi tạo và vẽ chart
            var chart = new google.visualization.BarChart(
                document.getElementById('barchartContainer')
            );
            chart.draw(data, options);
            
            // 4. Responsive: Redraw khi resize window
            window.addEventListener('resize', function() {
                drawChart();
            });
        }
    </script>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 2rem; background: #fafafa; }
        .chartWrapper { max-width: 800px; margin: 0 auto; background: white; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.05); }
        h1 { text-align: center; color: #2c3e50; margin-bottom: 1.5rem; }
    </style>
</head>
<body>
    <h1>Thêm Google Charts vào Website</h1>
    <div class="chartWrapper">
        <div id="barchartContainer"></div>
    </div>
</body>
</html>

Các loại biểu đồ phổ biến (Packages)

Loại biểu đồ Package Class JS
Line Chartcorechartgoogle.visualization.LineChart
Bar / Column Chartcorechartgoogle.visualization.BarChart / ColumnChart
Pie / Donut Chartcorechartgoogle.visualization.PieChart
Area Chartcorechartgoogle.visualization.AreaChart
Scatter Chartcorechartgoogle.visualization.ScatterChart
Geo Chart (Map)geochartgoogle.visualization.GeoChart
Gaugegaugegoogle.visualization.Gauge
Tabletablegoogle.visualization.Table

Nâng cao: Đọc dữ liệu từ Google Sheets

function drawChart() {
    var query = new google.visualization.Query(
        'https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/gviz/tq?sheet=Sheet1'
    );
    query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
    if (response.isError()) { console.error(response.getMessage()); return; }
    var data = response.getDataTable();
    // ... options & chart.draw(data, options)
}

Cách này cho phép cập nhật dữ liệu biểu đồ bằng cách chỉnh Google Sheets, không cần sửa code.

Lưu ý quan trọng

  • Google Charts load bất đồng bộ - luôn dùng callback.
  • Container phải có kích thước (width/height) trước khi draw.
  • Responsive: Gọi lại drawChart() khi window.resize (debounce 200ms).
  • Tùy chỉnh tooltip: tooltip: { isHtml: true } + set column role 'tooltip' trong DataTable.
  • License: Miễn phí, nhưng dữ liệu gửi đến Google để render (không phù hợp data nhạy cảm).