Issues with setting query ranges on google charts - javascript

I'm fairly new to coding with google charts/javascript, and for some reason when I try to draw data from a spreadsheet I can't specify the range.I'm using a tiny example spreadsheet and it still won't work. My java code is below, and I've tried every url modification I could find. Using 'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0range=2:5'doesn't change the result.
Using 'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/gviz/tq?range=2:5'won't generate a chart even though excluding the range will.
The whole java code is here, what am I doing wrong?:
google.charts.load('current', {
'packages': ['line', 'corechart', 'table']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var queryString = encodeURIComponent('SELECT A, H, O, Q, R, U LIMIT 5 OFFSET 8');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0range=A1:C2' + queryString);
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var materialOptions = {
chart: {
title: 'Example Data'
},
width: 900,
height: 500,
series: {
0: {
axis: 'Miles'
},
1: {
axis: 'Heartrate'
}
},
axes: {
y: {
Miles: {
label: 'Miles Run'
},
Heartrate: {
label: 'Heart rate(BPM)'
}
}
}
};
function drawMaterialChart() {
var chartDiv = document.getElementById('chart_div');
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
}
drawMaterialChart();
}

parameters on the url need to separated by --> &
e.g. --> .../edit#gid=0&range=A1:C2
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['line', 'corechart', 'table']
});
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0&range=A1:C2');
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var materialOptions = {
chart: {
title: 'Example Data'
},
width: 900,
height: 500,
series: {
0: {
axis: 'Miles'
},
1: {
axis: 'Heartrate'
}
},
axes: {
y: {
Miles: {
label: 'Miles Run'
},
Heartrate: {
label: 'Heart rate(BPM)'
}
}
}
};
function drawMaterialChart() {
var chartDiv = document.getElementById('chart_div');
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
}
drawMaterialChart();
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
note: if you're going to include a query string,
the select statement needs to be within the range set on the url
currently, range only includes columns A thru C
but sql has H, O, Q, R, U
EDIT
drop the range and try using method setQuery to use a SQL statement...
query.setQuery('SELECT A, B, C LIMIT 3');
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['line', 'corechart', 'table']
});
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1BHeR6LetK5ztqvgIm53OpbNFjMttRICBBDR8j1yEAjg/edit#gid=0');
query.setQuery('SELECT A, B, C LIMIT 3');
query.send(handleSampleDataQueryResponse);
}
function handleSampleDataQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var materialOptions = {
chart: {
title: 'Example Data'
},
width: 900,
height: 500,
series: {
0: {
axis: 'Miles'
},
1: {
axis: 'Heartrate'
}
},
axes: {
y: {
Miles: {
label: 'Miles Run'
},
Heartrate: {
label: 'Heart rate(BPM)'
}
}
}
};
function drawMaterialChart() {
var chartDiv = document.getElementById('chart_div');
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
}
drawMaterialChart();
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

Google chart only loads on refresh of page

Am a beginner using google charts/js. My google chart below loads fine, however there are times when the chart area loads blank html, and when I refresh the page it displays correctly.
I'm not sure why this is. It seems to do this on all browsers. This seems to indicate it could be with Mozilla, but the problem persists...
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei.' '. $end.' '.$start); #imei=sys.arg[1] end=sys.arg[2] start=sys.arg[3]
?>
var jsonData = <?php echo $result; ?> //{"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {0: {viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
$(window).resize(function(){
drawChart()
});
});
</script>
when using a function inline / anonymously, although you can provide a name,
you will not be able to call that same function again, by it's name
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() { // <-- cannot call this again, no name needed
...
instead, declare the function separately, then pass a reference where needed,
using the name of the function
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
...
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
var jsonData = {"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {
0: {
viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {
viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {
0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_chart"></div>

country name not show on geochart

This is my code
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type='text/javascript'>google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization()
{
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0');
// query.setQuery('select A,B,C');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
colorAxis: {colors: ['#D95F0E','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FFF7BC','#FFF7BC','#FFF7BC','#FFF7BC',]},
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
datalessRegionColor: '#F5F0E7',
displayMode: 'regions',
enableRegionInteractivity: 'true',
resolution: 'countries',
sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
region:'world',
keepAspectRatio: true,
width:800,
height:600,
tooltip: {isHtml:'true',textStyle: {color: '#444444'}, trigger:'focus'}
};
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0,{
type:'string',
label : 'num of',
calc: function (dt, row) {
return {
v: dt.getValue(row, 1),
f: dt.getFormattedValue(row, 1) + ': (' + dt.getFormattedValue(row, 2) + ' .)'
}
}
}]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
chart.draw(view, options);
}
</script>
<div id='visualization'></div>
and the spreadsheet here https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0
I don't know why the country name in the first column not show on the geochart
and how can I customize the tooltips such as.. add line break instead of colon(:) I tried br / but it didn't work
anyone can help ?
Thanks
added the following properties to the calculated view field...
role: 'tooltip',
p: {html: true}
see following working snippet...
google.charts.load('current', {
callback: drawVisualization,
packages:['geochart']
});
function drawVisualization() {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1dTfxVvfDKn6iXn4W_m7HJ_86JOGNDsxYSSaXipEo0vM/edit#gid=0');
query.send(handleQueryResponseTR);
}
function handleQueryResponseTR(response) {
if (response.isError()) {
console.log('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
colorAxis: {colors: ['#D95F0E','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FEC44F','#FFF7BC','#FFF7BC','#FFF7BC','#FFF7BC',]},
backgroundColor: {fill:'#FFFFFF',stroke:'#FFFFFF' ,strokeWidth:0 },
datalessRegionColor: '#F5F0E7',
displayMode: 'regions',
enableRegionInteractivity: 'true',
resolution: 'countries',
sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
region:'world',
keepAspectRatio: true,
width:800,
height:600,
tooltip: {isHtml:'true',textStyle: {color: '#444444'}, trigger:'focus'}
};
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type:'string',
label : 'num of',
calc: function (dt, row) {
return dt.getFormattedValue(row, 1) + ': (' + dt.getFormattedValue(row, 2) + ' .)'
},
role: 'tooltip',
p: {html: true}
}]);
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
chart.draw(view, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id='visualization'></div>

Event click from google chart blocks pop-ups when I try to open a new window

An event click from a Google chart blocks pop-ups when I try to open a new window.
This is how I draw the chart:
printChart: function() {
var self = this;
google.load('visualization', '1', {
'packages': ['corechart'],
"callback": function() {
try {
showLoading('widget');
var data = google.visualization.arrayToDataTable([]);
data.addColumn('string', 'Classification');
data.addColumn('number', $.t('columnVisits'));
data.addColumn('number', $.t('columnContacted'));
data.addColumn('number', $.t('columnUnattended'));
data.addColumn('number', '');
data.addColumn({ type: 'string', role: 'annotation' });
//We add all the elements to the graph
var dataClassified = self.getClassifiedFromConfig();
_.each(dataClassified, function(element) {
var inactive = (element.Inactive <= 0 && element.Visits <= 0 && element.ActivitiesPhoneCalls <= 0) ? 1 : element.Inactive,
assigned = element.Assigned > 0 ? element.Assigned : 1;
data.addRow([
{
v: element.IdClassification.toString(),
f: element.Classification
},
element.Visits/assigned,
element.ActivitiesPhoneCalls/assigned,
inactive/assigned,
0, //empty column for placing the Cycle as an annotation at the end of the stacked bars.
element.Cycle + ' ' + $.t('days')
]);
});
var options = {
isStacked: true,
hAxis: {
format: '#%',
minValue: 0,
maxValue: 1,
textStyle: {
color: '#404040',
fontName: 'Roboto',
fontSize: 14
}
},
vAxis: {
textStyle: {
color: '#404040',
fontName: 'Roboto',
fontSize: responsiveFontSize
}
},
bar: {
groupWidth: '75%'
},
annotations: {
alwaysOutside: true,
stemColor: 'none', // eliminate the tick for the annotation
textStyle: {
fontName: 'Roboto',
fontSize: 14,
bold: false,
italic: false,
color: '#404040'
}
},
series: {
3: {
visibleInLegend: false
}
},
legend: {
position: 'top'
},
tooltip: {
trigger: 'none'
},
height: responsiveHeight,
width: '100%',
colors: ['#85ac1f', '#fccd3d', '#eaeaea'],
enableInteractivity: true
};
var chart = new google.visualization.BarChart(document.getElementById('portfolio-coverage-chart'));
google.visualization.events.addListener(chart, 'onmouseover', function(e){
self.mouseOverHandler(chart, data);
});
google.visualization.events.addListener(chart, 'select', function(e){
self.selectHandler(chart, data);
});
/*$('.portfolio-coverage-chart').on('click', function() {
self.selectHandler(chart, data);
});*/
chart.draw(data, options);
} catch (e) {
console.log("error printChart " + e);
} finally {
hideLoading('widget');
}
}
});
},
When the user clicks in a bar of my Google chart I call this event:
google.visualization.events.addListener(chart, 'select', function(e){
self.selectHandler(chart, data);
});
The "selectHandler" function:
selectHandler: function(chart, data) {
var self = this;
var id = 5;
var customView = "";
var elementClick = chart.getSelection();
if (elementClick.length > 0){
var row = elementClick[0].row,
column = elementClick[0].column;
if (column === 1) {
id = 5;
customView = "customview.visitcompanies";
} else if (column === 2) {
id = 6;
customView = "customview.contactcompanies";
} else if (column === 3) {
id = 7;
customView = "customview.unattendedcompanies";
} else {
return;
}
//nulls out the selection so we can select it again
chart.setSelection();
var idClassification = parseInt(data.getValue(row, 0));
var params = self.setParams(idClassification);
doDrilldown(id, customView, "companies", params);
}
}
And then, the "doDrillDown" method try to open a new window applying the window.open function:
// open entity page
var newTab = window.open(url, '_blank');
if (newTab) {
newTab.focus();
} else {
alert('Please allow popups for this website');
}
But the pop-ups of my website get blocked before opening a new window.
If instead of the event handler from google I call an on click event works as expected (the problem here is that the data from "chart.getSelection();" is not update, and I get the selection done before the last one):
$('.portfolio-coverage-chart').on('click', function() {
self.selectHandler(chart, data);
});
Why is this happening?

Turning Google trend visual query into Google GEOchart

I'm trying to pass some data from the Google trends to a Google chart but i'm getting the Incompatible data table: Error: Table contains more columns than expected (Expecting 2 columns) error
I just assumed it would work automatically from one I query it into a chart rather than get an error. The code i'm getting an error with is:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var findTitle = $(".input-wrapper input").val();
function drawChart() {
console.log(findTitle);
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=GEO_MAP_0_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (data, row) {
return data.getFormattedValue(row, 0);
},
type: 'string',
label: data.getColumnLabel(0)
}, 1]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_region_top'));
chart.draw(view, {
chartArea: {
height: '80%',
width: '100%'
},
});
chart.draw(data, {
width: 1000,
height: 500,
title: 'Tag: Battlefield 1',
colors: ['#ff0000'],
backgroundColor: '#2D2D2D',
legendTextStyle: { color: '#FFF', position: 'bottom' },
titleTextStyle: { color: '#FFF' },
hAxis: {
textStyle: {color: '#FFF'},
gridlines: {color: '#FFF'}
},
vAxis: {
textStyle: {color: '#FFF'},
gridlines: {color: '#FFF'}
}
});
});
}
Any help into why i'm getting this error and a solution is greatly appreciated :)
since the GeoChart expects two columns,
use a DataView to extract the first two columns from the DataTable
also, need to load 'geochart' package, see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['geochart']
});
function drawChart() {
var query = new google.visualization.Query('https://www.google.com/trends/fetchComponent?hl=en-US&q=battlefield%201&cid=GEO_MAP_0_0&export=3&w=500&h=300&gprop=youtube&date=today%201-m');
query.send(function (response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' - ' + response.getDetailedMessage());
return;
}
var view = new google.visualization.DataView(response.getDataTable());
view.setColumns([0, 1]);
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(view, {
legend: 'none'
});
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google line chart is not working

I'm working first time with google chart.i am trying to modify a bar chart to line chart in which i am facing an error "container is not defined". As a bar chart it is working fine and i am taking data as a json response my json response is like this.
[{"rate":0.7955,"month":"December"},{"rate":0.7822,"month":"November"},{"rate":0.7789,"month":"October"},{"rate":0.7915,"month":"September"},{"rate":0.7928,"month":"August"},{"rate":0.8002,"month":"July"},{"rate":0.8133,"month":"June"},{"rate":0.8218,"month":"May"},{"rate":0.8264,"month":"April"},{"rate":0.823,"month":"March"},{"rate":0.8201,"month":"February"},{"rate":0.8297,"month":"January"}]
and my js file is
var TUTORIAL_SAVVY = {
/*return google visualization data*/
getvisualizationData: function (jsonData) {
var point1, dataArray = [],
data = new google.visualization.LineChart();
data.addColumn('string', 'Rate');
data.addColumn('number', 'Marks in Mathematics');
data.addColumn({
type: 'string',
role: 'tooltip',
'p': {
'html': true
}
});
/* for loop code for changing inputdata to 'data' of type google.visualization.DataTable*/
$.each(jsonData, function (i, obj) {
point1 = "Rate : " + obj.rate + "";
dataArray.push([obj.month, obj.rate, TUTORIAL_SAVVY.returnTooltip(point1)]);
});
data.addRows(dataArray);
return data;
},
/*return options for line chart: these options are for various configuration of chart*/
getOptionForLinechart: function () {
var options = {
title:'Key Success Metrics over time across all channels',
'backgroundColor': 'transparent',
'width': 620,
'vAxis': {minValue:"0", maxValue:"100", gridlines:{count: 7} },
'chartArea': {top:"50", left: "40"},
'legend':{position: 'top', alignment: 'start' }
};
return options;
},
/*Draws a line chart*/
drawLineChart: function (inputdata) {
var lineOptions = TUTORIAL_SAVVY.getOptionForLinechart(),
data = TUTORIAL_SAVVY.getvisualizationData(inputdata),
chart = new google.visualization.LineChart(document.getElementById('student-line-chart'));
chart.draw(data, lineOptions);
/*for redrawing the line chart on window resize*/
$(window).resize(function () {
chart.draw(data, lineOptions);
});
},
/* Returns a custom HTML tooltip for Visualization chart*/
returnTooltip: function (dataPoint1) {
return "<div style='height:30px;width:150px;font:12px,roboto;padding:15px 5px 5px 5px;border-radius:3px;'>" +
"<span style='color:#68130E;font:12px,roboto;padding-right:20px;'>" + dataPoint1 + "</span>" ;
},
/*Makes ajax call to servlet and download data */
getStudentData: function () {
$.ajax({
url: '/bin/servlet/rate',
dataType: "JSON",
success: function (data) {
TUTORIAL_SAVVY.drawLineChart(data);
}
});
}
};
google.load("visualization", "1", {
packages: ["corechart"]
});
$(document).ready(function () {
TUTORIAL_SAVVY.getStudentData();
});
can anybody help ?

Categories