How to load two Google Line charts in one page? - javascript

I had a deep look at somewhat similar questions asked here and here. I tried their implementation. It didn't work !
Then I had a look at following link by Google : tow charts in one page. Followed the same procedure but still ended up showing only one chart at a time.
Below is my code :
<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="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!--Load the Ajax API-->
<script type="text/javascript">
google.load("visualization", "1", {packages:["line"]});
google.setOnLoadCallback(drawChart);
google.setOnLoadCallback(drawOutputChart);
function drawChart() {
var data = new google.visualization.DataTable(<?= $jsonAnalogTable ?>);
var options = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart = new google.charts.Line(document.getElementById('analogchart'));
chart.draw(data, options);
}
function drawOutputChart(){
var data2 = new google.visualization.DataTable(<?= $jsonOutputTable ?>);
var options2 = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart2 = new google.charts.Line(document.getElementById('outputChart'));
chart2.draw(data2, options2);
}
</script>
**HTML Code to call it : **
<table>
<tr>
<td>
<div id="analogchart" >
</div>
</td>
<td>
<div id="outputChart" >
</div>
</td>
</tr>
</table>
I seriously have no idea what is going wrong as it is able to show one chart at a time, but not both !

it is recommended to use loader.js vs. the older library jsapi
and don't need both for a Line chart
also, setOnLoadCallback should only be called once per page
which can be included in the load statement, as in the following example
try something like this...
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: function () {
drawChart();
drawOutputChart();
},
packages: ['line']
});
function drawChart() {
var data = new google.visualization.DataTable(<?= $jsonAnalogTable ?>);
var options = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart = new google.charts.Line(document.getElementById('analogchart'));
chart.draw(data, options);
}
function drawOutputChart(){
var data2 = new google.visualization.DataTable(<?= $jsonOutputTable ?>);
var options2 = {
chart: {
title: ' Data ',
is3D: 'true'
},
width: 550,
height: 350,
};
var chart2 = new google.charts.Line(document.getElementById('outputChart'));
chart2.draw(data2, options2);
}
</script>

Related

dynamic google chart, Can't add new data

I call updateChart(d) functions via ajax and pass new data.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var chart;
var dataTable;
var options;
var i = 1;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
dataTable = google.visualization.arrayToDataTable([
['Amplitude', 'time'],
['0', 0]
]);
options = {
title: '',
curveType: 'function',
legend: { position: 'bottom' }
};
chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(dataTable, options);
}
function updateChart(d) {
i++;
dataTable.setValue(i, d); // Вот тут
chart.draw(dataTable, options);
}
</script>
When I try to add the next value for the chart, it throws an error:
Uncaught Error: Invalid row index 2. Should be in the range [0-0]
I did not find any solutions on the Internet (This is for a robot, it swears that there is not enough text).
function updateChart(d) {
i++;
console.log(i+"======"+d);
//data.setValue(i,1,d);
data.addRow([String(i), Number(d)]);
chart.draw(data, options);
}

Uncaught (in promise) Error: Data for arrayToDataTable is not an array in visualizing data using https://www.google.com/jsapi

I am trying to visualize data from a javascript file as shown below.
data = [ ['Year','China','India'],
['C1960',1.83286768126466,1.96098348563911],
['C1961',-1.01552778731319,1.99843774000741],
['C1962',0.820455548748518,2.03190545392019],
.
.
.
['C1963',2.45764740395145,2.0569116837358],
['C2017',0.559121331017265,1.06259739387194],
['C2018',0.455899678672578,1.03732336037888],
['C2019',0,0]
];
The html code I am using is as below.
<html>
<head>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable( data );
var options = {
title: 'World Bank Data Visualization',
chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1300px; height: 600px;"></div>
</body>
</html>
I am getting the error as
Uncaught (in promise) Error: Data for arrayToDataTable is not an array.
at Object.gvjs_ll [as arrayToDataTable] (jsapi_compiled_default_module.js:188)
at drawChart (data.htm:9)
Can anyone help me please? When I am loading another javascript file like this, it perfectly works. I don't know what is wrong with my code.
In your html, you have a variable named data. Due to this, the variable data from data.js is shadowed. More detail about Variable Shadowing here.
To make your code work, change that variable name to something else.
Something like:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataVis = google.visualization.arrayToDataTable( data );
var options = {
title: 'World Bank Data Visualization',
chartArea: {left:'10%',top:'10%', width: '65%', height: '65%'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataVis, options);
}

Show google chart on button click

I have the following div on a page where I would like a google chart to load on a button click:
html:
<div class="row">
<div class="col-lg-12">
<div class="card mb-3">
<div class="card-header"><b>System Voltage</b></div>
<div class="card-body">
<div class="row">
<div class="col-md-12" id="line_chart" style="width:100%;height:360px;">
<!-- SHOW GOOGLE GRAPH HERE --> <button class="btn">Plot chart!</button>
</div>
</div>
</div>
</div>
</div>
</div>
Google Chart:
<script type="text/javascript">
$(document).ready(function() {
$(".btn").click(function() {
google.charts.load('current', {
packages: ['corechart'], callback: drawChart
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei);
$resultdata = json_decode($result, true);
?>
var jsonData = <?php echo $result; ?> //{"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'65%'},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
});
});
});
</script>
At the moment, the button appears, but nothing is happening on the click.
I am trying to follow this example.
EDIT:
I have updated the google charts to exclude the callback statement, and also added libraries I am using. The chart shows up perfectly well when not using the button, but I would like it to show only when the button is pressed.
<script type="text/javascript">
$(document).ready(function() {
$(".btn").click(function() {
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei);
$resultdata = json_decode($result, true);
?>
var jsonData = {"Battery Voltage, (A)":{"2017-11-11T00:00:00.000Z":12.3,"2017-11-11T00:01:00.000Z":12.35,"2017-11-11T00:02:00.000Z":12.6,"2017-11-11T00:03:00.000Z":12.7,"2017-11-11T00:04:00.000Z":12.8},"Battery Current, (A)":{"2017-11-11T00:00:00.000Z":1.3,"2017-11-11T00:01:00.000Z":1.4,"2017-11-11T00:02:00.000Z":1.5,"2017-11-11T00:03:00.000Z":1.6,"2017-11-11T00:04:00.000Z":1.7}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'65%'},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
});
});
});
</script>
Libraries:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
when using the promise returned from the load statement,
the callback is not needed...
change the load statement as follows...
google.charts.load('current', {
packages: ['corechart'],
}).then(function () {
also need to ensure the library is included...
<script src="https://www.gstatic.com/charts/loader.js"></script>
EDIT
note: the following library is old and should no longer be used, you can remove it.
<script src="https://www.google.com/jsapi"></script>
see the release notes for more info...
the load statement will wait for the document to load,
no need for --> $(document).ready
recommend loading google first, then wait for the button click...
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
$(".btn").click(function() {
var jsonData = {"Battery Voltage, (V)":{"2017-10-09T00:00:00.000Z":12.5,"2017-10-09T00:01:00.000Z":12.44,"2017-10-09T00:02:00.000Z":12.43}};
var chartData = [];
Object.keys(jsonData).forEach(function (column) {
chartData.push(['Datetime', column]);
Object.keys(jsonData[column]).forEach(function (dateValue) {
chartData.push([new Date(dateValue), jsonData[column][dateValue]]);
});
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'65%'},
title: 'Battery Voltage',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
});
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input class="btn" type="button" value="Draw Chart" />
<div id="line_chart"></div>
Add <script type="text/javascript" src="https://www.google.com/jsapi"> to the head of your html page to load the library for the chart
Maybe you forgot to import all the necessary files. Make sure you are importing the jquery cdn (or download the file to your server)
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
and google chart cdn
<script src="https://www.google.com/jsapi"></script>
and check if you need an API key to use the plugin.

Integrate google chart in Laravel5.0 with the data from mysql database

I want to integrate google chart in my laravel5.0 application. The data is in mysql database. As far I've done researching over internet is given bellow
controller part
public function index(){
$barChart= DB::table('clients')
->select('clients.ClientName','clients.Price')
->get();
$bar = json_encode($barChart);
return view('home')
->with('bar', $bar);
}
If I print $bar , the result is
[{"ClientName":"nayeem","Price":1000},{"ClientName":"Tusher","Price":1000},
{"ClientName":"Nirjon","Price":1000},{"ClientName":"Remon","Price":1000},
{"ClientName":"Navid","Price":1000},{"ClientName":"Erfan","Price":1000},
{"ClientName":"Sazzad","Price":1000},{"ClientName":"Farin","Price":2000},
{"ClientName":"Arman","Price":1000},{"ClientName":"Sohan","Price":1000},
{"ClientName":"romi vai","Price":9000},{"ClientName":"tasif","Price":1000},
{"ClientName":"trina","Price":1000},{"ClientName":"Nuru Vai","Price":1000}]
view part
<div class="panel-body" id="barChart"> </div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?=$bar?>);
var options = {
title: 'My Bar chart',
is3D: 'true'
};
var chart = new google.visualization.PieChart(document.getElementById('barChart'));
chart.draw(data, options);
}
But it shows "table has no column" . I know I haven't create any column and I also understand that simply writing this google.visualization.DataTable(<?=$bar?>) will not create any column. I've tried many ways to create column but can not find any solution. How can I create data table from this?
I also tried chartWraper
<script type="text/javascript">
google.load('visualization', '1.0');
function drawInventoryChart() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [], //don't know how to put $bar here
option: {title: 'test'}
});
wrapper.draw('barChart');
}
google.setOnLoadCallback(drawInventoryChart);
</script>
This also does not work as I can not properly have the value of dataTable[] .
you can use array.forEach to load the data into the data table.
see following example...
google.charts.load('current', {
callback: function () {
// use the following
//var sqlData = <?=$bar?>;
// for example
var sqlData = [
{"ClientName":"nayeem","Price":1000},{"ClientName":"Tusher","Price":1000},
{"ClientName":"Nirjon","Price":1000},{"ClientName":"Remon","Price":1000},
{"ClientName":"Navid","Price":1000},{"ClientName":"Erfan","Price":1000},
{"ClientName":"Sazzad","Price":1000},{"ClientName":"Farin","Price":2000},
{"ClientName":"Arman","Price":1000},{"ClientName":"Sohan","Price":1000},
{"ClientName":"romi vai","Price":9000},{"ClientName":"tasif","Price":1000},
{"ClientName":"trina","Price":1000},{"ClientName":"Nuru Vai","Price":1000}
];
// create data table
var data = new google.visualization.DataTable();
data.addColumn('string', 'Client');
data.addColumn('number', 'Price');
// load data table
sqlData.forEach(function(row) {
data.addRow([row.ClientName, row.Price]);
});
var chart = new google.visualization.BarChart(document.getElementById('barChart'));
chart.draw(data, {
title: 'My Bar chart',
is3D: 'true'
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="barChart"></div>

Google Chart with ajax

I can't see what i'm missing. I can't seem to get the Google chart api running with a little bit of ajax. What am I doing wrong?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataSet = $.ajax({
url: "phpdata.php",
async: false
}).responseText;
var data = google.visualization.arrayToDataTable([
dataSet
]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
my php data:
['year', 'fixedassets'],
['2009', 1],
['2010', 1.2],
['2011', 1.6]
I don't know if it would solve your issue, I was facing a similar issue while rendering partials called from ajax calls. The drawChart function was not being called which basically meant that the setOnLoadCallback was not firing as expected. To overcome that, I modified my calls as follows:
google.load("visualization", "1", {packages:["corechart"]});
//google.setOnLoadCallback(drawChart);
$(function() {
drawChart(); //works
});
function drawChart() {
}
So basically I left the google method , and made my own self calling function which gets called whenever the page renders or the div is updated.
The problem is likely with your ajax call:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var dataSet = [ ['year', 'fixedassets'],['2009', 1],['2010', 1.2],['2011', 1.6]];
var data = google.visualization.arrayToDataTable(dataSet);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
This works, so it's not a problem with any of the existing code. Your format for the ajax call is using a bunch of depreciated jQuery calls, and without access to your server I can't test it, but you could try something like:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get("phpdata.php", function(response_data) {
var data = google.visualization.arrayToDataTable([response_data]);
var options = {
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
and see if that works.
I think that the problem you're having is that you have a string: "['year', 'fixedassets'], ['2009', 1], ['2010', 1.2], ['2011', 1.6]" and you want it evaluated as an array: [['year', 'fixedassets'],['2009', 1],['2010', 1.2],['2011', 1.6]]. The easy-but-insecure way to solve this is to use eval(). you'd say:
$.get("phpdata.php", function(response_data) {
var data = google.visualization.arrayToDataTable(eval('[' + response_data + ']');
This is not-great-but-working as long as you completely control the server, and you're not getting any user input that could be sent from your server.
The 'right' way to do this would be to send actual json from your server, instead of sending what you're sending, and then use JSON.parse(response_data).

Categories