Cannot read property '0' of undefined google chart - google-visualization

I get this error message "Cannot read property '0' of undefined google chart" when i load my 2 graphs and it only occurs when i load my page for the first time. If i click F5 on chrome they load properly. If i resize the browser they appear load properly. What could be the problem ? IE shows this error once, Chrome shows it every time i open the page for the first time. Some times i get this error when i load my page :
0x800a138f - JavaScript runtime error: Unable to get property 'arrayToDataTable' of undefined or null reference
Please see my code below :
<script src="../Scripts/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart1);
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart2);
$(window).resize(function () {
if (width != $(window).width() || height != $(window).height()) { //only refresh if screen size changes
drawChart1();
drawChart2();
width = $(window).width();
height = $(window).height();
}
});
$(document).ready(function () {
width = $(window).width();
height = $(window).height();
});
function drawChart1() {
var data = google.visualization.arrayToDataTable([
['Minute', 'Users'],
['0 Min', 9],
['1 Min', 28],
['2 Min', 1],
['3 Min', 1],
['5 Min', 1]
]);
var options = {
slices: {
0: { offset: 0.2 }
},
chartArea: { 'left': '5%', 'top': '10%', 'width': '100%',
'height': '100%' }
};
var chart = new
google.visualization.PieChart(document.getElementById('graph1'));
chart.draw(data, options);
}
function drawChart2() {
var data = google.visualization.arrayToDataTable([
['Minute', 'Users'],
['0 Min', 20],
['4 Min', 4],
['5 Min', 1],
['8 Min', 8],
['10 Min', 3]
]);
var options = {
// title: 'Group C Users'
pieHole: 0.5,
chartArea: { 'left': '5%', 'top': '10%', 'width': '100%',
'height': '100%' }
};
var chart = new
google.visualization.PieChart(document.getElementById('graph2'));
chart.draw(data, options);
}

first, you can remove jsapi, it is no longer being used...
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
next, you only need to call google.charts.load one time,
you can also include the callback in the load statement.
try replacing this...
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart1);
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart2);
with this...
google.charts.load('current', {
packages: ['corechart'],
callback: function () {
drawChart1();
drawChart2();
}
});

Related

Resource interpreted as Document but transferred with MIME type image/octet-stream

Using the following code to save a Google chart. But it is getting downloaded as a file and not an image, it was throwing following
"Resource interpreted as Document but transferred with MIME type image/octet-stream: "data:image/octet-stream;base64,..."
And the code:
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('div')[1];
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
function saveAsImg(chartContainer) {
var imgData = getImgData(chartContainer);
window.location = imgData.replace("image/png", "image/octet-stream");
}
you can use an anchor tag with a download attribute to assign the file name
and most charts have a getImageURI method
also, don't see the need to replace("image/png", "image/octet-stream")
see following working snippet...
google.charts.load('current', {
callback: function () {
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
// set anchor tag
var saveLink = document.getElementById('saveLink');
saveLink.href = chart.getImageURI();
// cause download to occur
saveLink.click();
});
chart.draw(google.visualization.arrayToDataTable([
['Task', 'Hours'],
['A', 19.2],
['B', 30.8],
['C', 50.0]
]), {
height: 200,
chartArea: {
top: 24
},
legend: 'none',
pieHole: 0.4,
theme: 'maximized',
width: 200
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<a id="saveLink" download="chart.png">Save Chart</a>

Google halfdonut pie chart: is it possible to set total percentage?

I made half a donut chart with Google charts and I have a problem that the sum of visible percentage is equal to 50%. Is there any possible solution ?
Image of my chart
you can override the text displayed on the slice by using the following config option...
pieSliceText: 'value'
then in the data, set the formatted value of the cells to the correct percentage...
var data = [
['Task', 'Hours'],
// use formatted values
['A', {v: 19.2, f: '38.4%'}],
['B', {v: 30.8, f: '61.6%'}],
[null, 50]
];
the following working snippet uses the same approach,
but calculates the correct percentages,
rather than hard-coding...
google.charts.load('current', {
callback: function () {
var data = [
['Task', 'Hours'],
['A', 19.2],
['B', 30.8],
[null, 50.0]
];
var total = 0;
for (var i = 1; i < data.length; i++) {
if (data[i][0] !== null) {
total += data[i][1];
}
}
var numberFormat = new google.visualization.NumberFormat({
pattern: '#,##0.0',
suffix: '%'
});
var dataTable = google.visualization.arrayToDataTable(data);
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
if (dataTable.getValue(i, 0) !== null) {
dataTable.setFormattedValue(i, 1, numberFormat.formatValue(((dataTable.getValue(i, 1) / total) * 100)));
}
}
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
var options = {
height: 400,
chartArea: {
top: 24
},
colors: ['#8BC34A', '#64B5F6'],
legend: 'none',
pieHole: 0.4,
pieStartAngle: 270,
pieSliceText: 'value',
slices: {
2: {
color: 'transparent'
}
},
theme: 'maximized',
width: 400
};
chart.draw(dataTable, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google charts legend customize

I have two series/columns fileSize and output Target.
Is it possible two display only output Target in the legend and hide fileSize?
you can use the visibleInLegend configuration option
just assign to the series number
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['File', 'fileSize', 'output Target'],
['a', 10, 15],
['b', 12, 18],
['c', 14, 21],
['d', 16, 24]
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(container);
chart.draw(data, {
legend: {
position: 'bottom'
},
series: {
0: {
visibleInLegend: false
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Hide text from Google GeoChart tooltip

I have a Google Geochart that is connected to a Google Spreadsheet. The aim of the chart is to show different categories of universities in our state and their locations. I have assigned values in the spreadsheet in order to have the appropriate marker color for the map to denote the categories.
My problem is that the text denoting the type (a number) is showing in the tooltip. (Example: tooltip shows "ABC University Type 3." I need to either hide this text, or create a string based on conditional logic so that, for example, Type 3 translates to "XYZ System" in the tooltip. Which do you think is the better way to do it, and can you provide guidance as to how to do this?
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
google.charts.load('current', { 'packages': ['geochart'] });
google.charts.setOnLoadCallback(drawMap);
function drawMap() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1m3ujxzPQJh3haReNDzGGF73Mh6-u6HxyCVPK_5MK2hw/gviz/tq?sheet=Sheet3");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {var data = response.getDataTable();
var options = {
//showTip: true,
mapType: 'styledMap',
useMapTypeControl: true,
resolution: 'provinces',
//displayMode: 'text',
//magnifyingGlass: {'enable': true, 'zoomFactor': '7'},
region: 'US-KY',
keepAspectRatio: true,
legend: 'none',
sizeAxis: { minValue: 1, maxValue: 3, minSize: 10, maxSize: 10 },
colorAxis: {colors: ['green', 'blue', 'purple'], values: [1, 2, 3]},
markerOpacity: 0.75,
tooltip: {showColorCode: false, isHTML: true, textStyle:{fontSize: 21}},
dataMode: 'markers'
};
var map = new google.visualization.GeoChart(document.getElementById('chart_div'));
map.draw(data, options);
};
</script>
<style type="text/css">
html, body {height: 100%;}
#chart_div {width: 100%; height: 100%;}
</style>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
You can use the DataView Class to change the formatted value of the Type column.
For instance, the value of the Type column in the DataTable looks like this...
{"v":3.0,"f":"3"}
With the DataView, change it to this...
{"v":3.0,"f":"XYZ System"}
We can also remove the column Label, to avoid seeing it in the tooltip.
See following example...
google.charts.load('current', {
callback: drawMap,
packages: ['geochart']
});
function drawMap() {
var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1m3ujxzPQJh3haReNDzGGF73Mh6-u6HxyCVPK_5MK2hw/gviz/tq?sheet=Sheet3");
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
var data = response.getDataTable();
// setup school type array
var schoolTypes = [
'ABC System',
'LMO System',
'XYZ System'
];
// create DataView from DataTable
var view = new google.visualization.DataView(data);
// set view columns, keep first three columns
// use calculated column for Type
view.setColumns([0, 1, 2, {
type: 'number',
label: '',
calc: function (dataTable, rowIndex) {
return {
v: dataTable.getValue(rowIndex, 3),
// get school type from array
f: schoolTypes[dataTable.getValue(rowIndex, 3) - 1]
}
}
}]);
var options = {
//showTip: true,
mapType: 'styledMap',
useMapTypeControl: true,
resolution: 'provinces',
//displayMode: 'text',
//magnifyingGlass: {'enable': true, 'zoomFactor': '7'},
region: 'US-KY',
keepAspectRatio: true,
legend: 'none',
sizeAxis: { minValue: 1, maxValue: 3, minSize: 10, maxSize: 10 },
colorAxis: {colors: ['green', 'blue', 'purple'], values: [1, 2, 3]},
markerOpacity: 0.75,
tooltip: {showColorCode: false, isHTML: true, textStyle:{fontSize: 21}},
dataMode: 'markers'
};
var map = new google.visualization.GeoChart(document.getElementById('chart_div'));
map.draw(view, options);
};
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
ALSO -- Recommend including loader.js and jsapi only once per page

Can any tell me how add two needles in Gauge graph Using Google charts

I want to display two values in a single gauge graph using two needles. How can I do that.
Can any one please suggest me of doing it.
I have tried with following code But I am not success full.
And I got this following error.
GET http://5.39.186.164/%7B%22cols%22:[%7B%22label%22:%22Q7%22,%22type%22:%22nu…r%22%7D],%22rows%22:[%7B%22c%22:[%7B%22v%22:43%7D,%7B%22v%22:21%7D]%7D]%7D 404 (Not Found)
<!--Load the AJAX API -->
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['gauge']});
</script>
<script type="text/javascript">
var gauge;
var gaugeData;
var gaugeOptions;
function drawGauge() {
//var response = '<?php echo json_encode($response); ?>'; alert(' hi ' + response);
//var obj = eval ("(" + response + ")");
$.getJSON('<?php echo json_encode($response); ?>', function(json) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
for (x in json) {
data.addRow([x, json[x]]);
}
//gaugeData = new google.visualization.DataTable(response);
gauge = new google.visualization.Gauge(document.getElementById('gauge'));
gaugeOptions = {
width: 2000,
height: 150,
greenFrom: 0,
greenTo: 50,
redFrom: 75,
redTo: 100,
yellowFrom:50,
yellowTo: 75,
minorTicks: 5
};
gauge.draw(gaugeData, gaugeOptions);
//chart.draw(data, options);
});
}
google.load('visualization', '1', {packages:['gauge'], callback: drawGauge});