Insert google chart?

Not sure where to start with this - trying any of the sample code posted here https://developers.google.com/chart/interactive/docs/basic_load_libs doesn't work and I'm sure it's the starting point of referencing the google javascript api that's the problem.  How should this sample code be modified to work for Knack? 

// Load the Visualization API and the piechart package.
      google.load('visualization', '1.0', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.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'));
  chart.draw(data, options);
}</pre><p></p><p>&nbsp;</p>

Try this simplified code instead! Tips for use:

1) modify the view number to fit yours (this code requires you to have a table with all your data on the same page)

2) check your data structure with the console log

3) use the console log to change the field numbers referenced. 

4) turn off the comment code for the last section to activate the visual

 

$(document).on('knack-view-render.view_684', function(event, view, data) {
$('<div id="chart_div" style="height: 500px;"></div>').insertBefore($("#view_684"));

var mydata = Knack.models['view_684'].data.toJSON();
console.log('mydata');
console.log(mydata);

google.charts.load('current', {packages: ['timeline']});
google.charts.setOnLoadCallback(drawSeries);

/* //<--delete this once you have adapted the fields in the 'get each mydata items' section to fit your 'mydata'. Use console log to check your own object names.
var data_array = new Array();
data_array.push(['categories', 'events', { role: "tooltip" }, 'Start', 'End']);


//get each mydata items
for (x = 0; x < mydata.length; x++) {
thisrow = mydata[x];
var category = thisrow.field_184; //any text field
var event = thisrow.field_211; //any text field
var tooltip = thisrow.field_165 //any text field, or a combination of multiple text fields
var time = thisrow.field_164_raw; //must be a time field with to and from
var time1u = time.unix_timestamp;
var time2u = time.to.unix_timestamp;
var time1=new Date(time1u)
var time2=new Date(time2u)
var add_arr = [ category, event, tooltip, time1, time2 ];
data_array.push(add_arr);
};
//end get each mydata items

console.log('data_array');
console.log(data_array);



function drawSeries() {
var data = google.visualization.arrayToDataTable(data_array);

var options = {
chartArea: {left: 200, width: 1050, height: 1000},
title: 'Timeline',
timeline: { rowLabelStyle: {fontName: 'Tahoma', fontSize: 12},
barLabelStyle: { fontName: 'Tahoma', fontSize: 12 }},
timeline: {colorByRowLabel: true},
timeline: {avoidOverlappingGridLines: false}
};
var chart = new google.visualization.Timeline(document.getElementById('chart_div'));
chart.draw(data, options);

};

*/ //<-- delete this one as well
});

1 Like

Did you guys have any trouble 'GET'ting the view-based request. For the life of me, I can't get the API to pull any records on the request. Any insight?

Thank you so much for the example! 

I've built on your code to create a timeline with cars and trips - posting it here if anyone is looking for something similar. 

I haven't been able to set up any interactive filtering of the chart yet - has anyone been able to do that? For example, I'd like to show only Friday trips by clicking a filter button. Or would I need to hardcode it into multiple charts?

 

LazyLoad.js(['https://www.gstatic.com/charts/loader.js'], function () {
console.log('Loaded: https://www.gstatic.com/charts/loader.js');
});

$(document).on('knack-view-render.view_537', function(event, view, data) {
$('<div id="chart_div" style="height: 500px;"></div>').insertBefore($("#view_537"));
});

$(document).on('knack-view-render.view_537', function(event, view, data) {

google.charts.load('current', {packages: ['timeline']});
google.charts.setOnLoadCallback(load_page_data);

var data_array = new Array();
data_array.push(['bil', 'tur', { role: "tooltip" }, 'Start', 'End']);

function load_page_data(){
$.ajax({
url: 'https://api.knack.com/v1/pages/scene_69/views/view_516/records',
type: 'GET',
dataType: 'json',
headers: {
"Authorization": user,
'X-Knack-Application-Id':'********',
'X-Knack-REST-API-Key': "********",
'Content-Type': 'application/json'
},
success: function( data ) {
$.each( data.records , function (key,val) {
var bil = val.field_158;
var tur = val.field_212;
var sjaf = val.field_143;
var tid = val.field_164_raw;
var tid1u = tid.unix_timestamp;
var tid2u = tid.to.unix_timestamp;
var maxpax=val.field_283
var tid1=new Date(tid1u)
var tid2=new Date(tid2u)
var add_arr = [ bil, tur, sjaf, tid1, tid2 ];
if (maxpax > 0) {
data_array.push(add_arr);
}
});
drawSeries(data_array);
},
error: function() { console.log('error!'); },
});
};

function drawSeries() {

var data = google.visualization.arrayToDataTable(data_array);

var options = {
chartArea: {left: 200, width: 1050, height: 1000},
title: 'Bilplan',
timeline: { rowLabelStyle: {fontName: 'Tahoma', fontSize: 12},
barLabelStyle: { fontName: 'Tahoma', fontSize: 12 }},
timeline: {colorByRowLabel: true},
timeline: {avoidOverlappingGridLines: false}
};
var chart = new google.visualization.Timeline(document.getElementById('chart_div'));
chart.draw(data, options);
};
});

Jorgen,

 

  Thanks for the reminder, I should have posted back here.   We did get it working and for one of our apps, we use it 4 or 5 different times.   I will post the code we used and then to configure the chart I would just encourage you to reference google chart documentation as there are many options.  I will say I much prefer the Knack charts for functionality but the google charts have many more options, but type and visual customization.

*** Replace my views, fields, and app_ids with your own.   This is a copy of the code we put in place some time back but has been working so hopefully will help you out.  Best of luck.

 

 


$(document).on('knack-view-render.view_1791', function(event, view, data) {
$('<div id="chart_div"></div>').insertAfter($("#view_1791"));
});

$(document).on('knack-view-render.view_1791', function(event, view, data) {

google.charts.load('current', {packages: ['corechart','bar']});
google.charts.setOnLoadCallback(load_page_data);

var data_array = new Array();
data_array.push(['Tail', 'Operational Utilization', { role: "annotation" }]);

function load_page_data(){
$.ajax({
url: 'https://api.knack.com/v1/pages/scene_646/views/view_1867/records',
// url: 'https://api.knack.com/v1/objects/object_30/records',
// url: 'https://api.knack.com/v1/data/object_30/records?filters={"match":"and","rules":[{"field":"field_775","operator":"is+not","value":"T3"},{"field":"field_775","operator":"is+not","value":"C3"}]}&page=1&rows_per_page=50',
type: 'GET',
dataType: 'json',
headers: {
'X-Knack-Application-Id':'********',
'X-Knack-REST-API-Key': "********",

'Content-Type': 'application/json'
},
success: function( data ) {
$.each( data.records , function (key,val) {
var tn = val.field_775;
var ou = val.field_632_raw;
var an = val.field_632;
var add_arr = [ tn , ou, an ];
data_array.push(add_arr);
});
drawSeries(data_array);
console.log('Operational Utilization');
},
error: function() { console.log('error!'); },
});
};

function drawSeries() {
// console.log(data_array);

var data = google.visualization.arrayToDataTable(data_array);

var options = {
chartArea: {left: 100, width: 1050},
title: 'Operational Utilization Ratio - Last 30 Days (Total Hours Flown / Total Hours Available)',
// animation: {startup: true, duration: 1000, easing: 'out',},
width: 1200,
height: 300,
colors: ['#90be75'],
annotations: { alwaysOutside: true, format: 'Percent', datum: {style: {color: 'black'} }, textStyle: { color: 'black'} },
legend: { position: 'none' },
vAxis: { title: 'Operational Utilization', format: 'Percent' },
hAxis: { textStyle: {fontSize: 12}}

};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
// console.log(options);
};

});

Brad - I feel like things are pushing me this direction again.  I see you have made some serious progress, congrats.  Just wanted to know if you did get it working with Knack data.  If so i will get to work. :)

UPDATE: Proof of concept working with sample data from Google's examples.

Next step will be to use Knack data of course.

--------------------------------------------

LazyLoad.js(['https://www.gstatic.com/charts/loader.js'], function () {
  console.log('Loaded: https://www.gstatic.com/charts/loader.js');
});

$(document).on('knack-view-render.view_21', function(event, view, data) {
 
  // Load the Visualization API library and the Gantt chart.
  // See https://developers.google.com/chart/interactive/docs/gallery/ganttchart
  google.charts.load('current', {'packages':['gantt']});
  google.charts.setOnLoadCallback(drawChart);

    function daysToMilliseconds(days) {
      return days * 24 * 60 * 60 * 1000;
    }

    function drawChart() {

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Task ID');
      data.addColumn('string', 'Task Name');
      data.addColumn('date', 'Start Date');
      data.addColumn('date', 'End Date');
      data.addColumn('number', 'Duration');
      data.addColumn('number', 'Percent Complete');
      data.addColumn('string', 'Dependencies');

      data.addRows([
        ['Research', 'Find sources', new Date(2015, 0, 1), new Date(2015, 0, 5), null,  100,  null],
        ['Write', 'Write paper', null, new Date(2015, 0, 9), daysToMilliseconds(3), 25, 'Research,Outline'],
        ['Cite', 'Create bibliography', null, new Date(2015, 0, 7), daysToMilliseconds(1), 20, 'Research'],
        ['Complete', 'Hand in paper', null, new Date(2015, 0, 10), daysToMilliseconds(1), 0, 'Cite,Write'],
        ['Outline', 'Outline paper', null, new Date(2015, 0, 6), daysToMilliseconds(1), 100, 'Research']
      ]);

      var options = {height: 275};

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

      chart.draw(data, options);
    }

  $('#view_21 .view-header').after('<div id="chart_div" style="width:400; height:300"></div>');
});
Produces this:
 

Hey thanks again for the input Andrzej.  I've dropped this idea but i reckon I'll come back to it at some stage now that you rejuvenated it!  If I ever get a Gantt chart up using Knack data I'll be sure to share.

hi Brad,

Just an idea. I have managed to make it work, but I am embedding Knack inside my page, so I have put 

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

into my <head> section and rest code in knack javascript scene render event handler. Works well that way inside knack.

Hope this would help you to find the reason why it wasn't working for you.

Andrzej

No I didn't Mac, dropped the idea.  Can't see why it wouldn't work though and I'm sure my coding was the problem.

did you ever get this one figured out?

Still stuck - Have tried adding the code to a page render which doesn't call the drawChart function.

 

$(document).on('knack-page-render.scene_3', function(event, page) {
  // Load the Visualization API library and the piechart library.
  google.load('visualization', '1.0', {'packages':['corechart']});
  google.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'));
  chart.draw(data, options);
}

$(’#view_175 .view-header’).after(’<div id=“chart_div” style=“width:400; height:300”></div>’);
});