Search code examples
google-apps-scriptgoogle-app-maker

Using the Charts API to create a scatter chart in Google AppMaker


Appmaker has builtins for Line and Bar charts, but not for Scatter charts.

It appears that I can access Charts.newScatterChart() from within AppMaker scripts (it shows up in the autocomplete when I try to use it in a script). However, I don't see how to display those charts in the UI.

How do I use the Charts API to create a scatter chart and display it in my AppMaker UI?


Solution

  • Unfortunately, App Maker will not help you a lot with charts that it doesn't support out of the box. So, we will need to go through excited journey.

    1. First things first we need to figure out concurrency. We need to have chart script on the client before we receive data to render to avoid numerous reperetive checks and inline initializations. In order to do that we need to add visualization library of choice as external JavaScript resource and handle its load. In this answer I'll use Google's Material Scatter Chart for reference. Here is a link to its loader library https://www.gstatic.com/charts/loader.js
    // onAppStart event handler
    loader.suspendLoad();
    
    google.charts
          .load('current', { 'packages': ['scatter'] })
          .then(function(){
             loader.resumeLoad();
          });
    

    The result of the first step will look like this Initialize chart

    1. Prepare your data model. It can be either Calculated or real one. The model should contain at least to numeric fields (one for x-axis and one for y-axis).
    2. Add container for the chart in can be HTML or Panel widget.
    3. Bind your widget container to the model's datasource
    4. Map datasource's items to chart's DataTable
    // chart container's onDataLoad event handler
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'X');
    data.addColumn('number', 'Y1');
    data.addColumn('number', 'Y2');
    
    var rows = [];
    
    widget.datasource.items.forEach(function(item) {
      rows.push([item.X, item.Y1, item.Y2]);
    });
    
    data.addRows(rows);
    
    var chart = new google.charts.Scatter(widget.getElement());
    
    // If you are using built-in App Maker charts you can
    // encounter this issue https://stackoverflow.com/questions/35636075
    chart.draw(data);