Search code examples
javascriptgoogle-visualizationgoogle-query-language

Pass Custom Parameter to query.send Google Query Language


I am using google's charts API to create a web-based dashboard. I want to draw many graphs and need to pass custom parameters to the handleDataQueryResponse function from this link: https://developers.google.com/chart/interactive/docs/spreadsheets#sheet-name. This function is called via a query.send(handleDataQueryResponse) call. I would have thought I could do this by calling: query.send(function() { handleDataQueryResponse(parameters) }); but this hasn't been working for me. Any ideas? Open to other approaches to making the query and its handler reusable!

More info on google's javascript chart API here: https://developers.google.com/chart/interactive/docs/quick_start.


Solution

  • I figured out one solution, and let me tell you, it's not pretty. But it works. As always, happy for improvements and feedback! Thanks @WhiteHat for helping me out.

    google.charts.setOnLoadCallback(function() {
        drawChart('chart1', 0, 'SELECT A, B, C, D, E', {title: 'Chart 1'})
    
        drawChart('chart2', 1, 'SELECT A, H, I, J', {title: 'Chart 2'})
    });
    
    var chartsArray = [];
    var optionsArray = [];
    var nextID = 0;
    
    function drawChart(tag, id, sqlCommand, options= {}, sheetName='Sheet1', numHeaders=1) {
        chartsArray[id] = new google.visualization.ColumnChart(document.getElementById(tag));
    
        optionsArray[id] = options;
    
        var queryString = encodeURIComponent(sqlCommand);
    
        var query = new google.visualization.Query(
           'https://docs.google.com/spreadsheets/d/1dfRA_NDsdfED3OEdx-v3ZzA2-oWPS4kU_2mV-PY/gviz/tq?sheet=' + sheetName + '&headers=' + numHeaders.toString() + '&tq=' + queryString);
          query.send(handleDataQueryResponse);
    }
    
    function handleDataQueryResponse(response, id) {
        if (response.isError()) {
          alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
          return;
        }
    
        var data = response.getDataTable();
        chartsArray[nextID].draw(data, optionsArray[nextID]);
        nextID += 1;
    }