I have problem when I want to show my treemap chart in browser. When I call my testingTreemap.php, my browser didn't show anything, just the tittle. I confuse how to set my data become values in treemap chart.
This is my testingTreemap.php
google.charts.load('current', {'packages':['treemap']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
//var dataFromPHP = <?php echo file_get_contents('clientdata.json'); ?>;
$dataFromPHP = file_get_contents('clientdata.json');
$json = json_decode($dataFromPHP, TRUE);
// console.log(dump_dataFromPHP);
$provinsi = 'SELECT provinsi , LEFT(provinsi, '') AS lala FROM data_client';
$query = 'SELECT provinsi ,kode_sales, gaji, count(kode_sales) AS T_nasabah FROM data_client GROUP BY kode_sales';
//var newData = [];
['Location', 'Parent' , 'Size', 'Color'];
$exec = mysqli_query($con,$query);
$execProv = mysqli_query($con,$provinsi);
echo "['".$row['lala']."'," null, 0, 0"],";
while($row = mysqli_fetch_array($execProv)){
echo "['".$row['provinsi']."','".$row['lala']."',"0,0"],";
}
while($row = mysqli_fetch_array($exec)){
echo "['".$row['kode_sales']."','".$row['provinsi']."',".$row['gaji'].",".$row['T_nasabah']."],";
}
//console.log(dataFromPHP);
console.log((data));
tree = new google.visualization.TreeMap(document.getElementById('chart_div'));
tree.draw(data, {
minColor: '#f00',
midColor: '#ddd',
maxColor: '#0d0',
headerHeight: 15,
fontColor: 'black',
showScale: true
});
chart.draw(data, options);
}
})
And always to getting "SyntaxError: missing ; before statement" on this line (btw I got this line after I run php file and from Google Chrome > Right click > Inspect Element > Console)
function drawChart(){
//var dataFromPHP = [
{
"kode_client": "CLI01", <<<------- SyntaxError: missing ; before statement
"nama": "Edo",
"tanggal_lahir": "01\/05\/1967",
"alamat": "Nusa Hijau",
"telp": "085634234",
"produk": "Titanium",
"gaji": "5000000",
"cabang": "Bandung",
"provinsi": "Jawa Barat",
"kode_sales": "CLI02"
},
{
"kode_client": "CLI02",
"nama": "Santoso Imam",
"tanggal_lahir": "15\/12\/1979",
"alamat": "Padasuka",
"telp": "08513087645",
"produk": "Investra Link",
"gaji": "4500000",
"cabang": "Cimahi",
"provinsi": "Jawa Tengah",
"kode_sales": "SAL04"
}
it is recommended to use the following library when loading google charts...
<script src="https://www.gstatic.com/charts/loader.js"></script>
and if using loader.js, the load statement is incorrect...
google.charts.load('visualization', {packages:['treemap']}); //<-- wrong
should be...
google.charts.load('current', {'packages':['treemap']});
the first argument should be the version to load
when using the older jsapi library,
the load statement would look something like this...
google.load('visualization', '1', {packages:['treemap']});
but according to the release notes
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently.
EDIT
this line is incorrect...
echo "['".$row['provinsi']."','".$row['lala']."',"0,0"],";
change to...
echo "['".$row['provinsi']."','".$row['lala']."',0,0],";
Related
I need to create a data table to pass a google chart starting from an array: I retrieve data, as example temperature, from OpenWeather API in PHP and I convert the temperature array into a javascript array. From this array I build the data table with this code:
<script type="text/javascript">
var temp=new Array();
<?php
for($i=0;$i<count($temperatura);$i++){?>
temp[<?php echo $i; ?>]="<?php echo "$temperatura[$i]"; ?>";
<?php
}?>
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data2 = new Array();
data2[0] = [ 'Data', 'Temp.' ];
for (i = 0; i < temp.length; i++) {
data2[i + 1] = [ '10/04/2017', 'temp[i]' ];
}
var data = google.visualization.arrayToDataTable(data2, false);
document.write(data); //this cause the message [object Object]
var options = {
chart: {
title: 'Box Office Earnings in First Two Weeks of Opening',
subtitle: 'in millions of dollars (USD)'
},
width: 900,
height: 500,
axes: {
x: {
0: {side: 'top'}
}
}
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
}
</script>
<div id="chart_div"></div>
In the browser I see the message [object Object] and I don't understand what is wrong. Can help me?
I read some similar questions but they don't solve my problem.
What I want to do
I am trying to show data from a MySQL database in a "ComboChart" using Google Charts. In order to do that I followed this tutorial, made some alterations and came up with the code as shown on the very bottom of this post.
Actual behavior
The data displays correctly. I do have to tell Google Charts however that the "year" is a number what throws it into continuous "mode". That leads to the year on the hAxis displaying with decimal places, in particular if I don't have data for all consecutive years. (i.e. 2,010.5)
Desired behavior
I want Google Charts to display the year as if it was a string and operate in discrete "mode".
What I think the problem is
I think the problem, I am encountering is mostly due to the fact that the year (to be shown on the hAxis) is a int(11) in the database and that the json that is provided by a controller also has the year as a number. To clarify below an example of what the json could look like:
[
{
"year_data": 2010,
"data_1": 125895,
"data_2": 25158.5
}
]
As I use the controller for a bunch of other stuff, I would preferably not make any alterations to it.
What I tried to fix it
I tried the bold move of just changing data.addColumn('number', 'year_data'); to data.addColumn('string', 'year_data');. It didn't work and I got a "type mismatch".
I tried to come up with a workaround mostly involving hAxis.showTextEvery: and some sort of row count. It didn't work but that might very well be due to my lack of experience/knowledge.
The question in one sentence
How can I turn the year data into a string in JavaScript or having Google Charts behave as if it was a string?
Code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script src="/googlecharts/ajaxGetPost.js" type="text/javascript"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
function charts(data, ChartType) {
var jsonData = data;
google.load("visualization", "1", {
packages: ["corechart"],
callback: drawVisualization
});
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'year_data');
data.addColumn('number', 'Data 1');
data.addColumn('number', 'Data 2');
$.each(jsonData, function(i, jsonData) {
var year = jsonData.year_data;
var data1 = jsonData.data_1;
var data2 = jsonData.data_2;
data.addRows([
[year, data1, data2]
]);
});
var options = {
colorAxis: {
colors: ['#54C492', '#cc0000']
},
datalessRegionColor: '#dedede',
defaultColor: '#dedede',
legend: {
position: 'bottom',
alignment: 'start'
},
seriesType: 'bars',
series: {
1: {
type: 'line'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
}
$(document).ready(function() {
url = '/data/get';
ajax_data('GET', url, function(data) {
charts(data)
});
});
</script>
toString should work just fine, see following snippet...
var data = new google.visualization.DataTable();
data.addColumn('string', 'year_data');
data.addColumn('number', 'Data 1');
data.addColumn('number', 'Data 2');
$.each(jsonData, function(i, jsonData) {
var year = jsonData.year_data.toString();
var data1 = jsonData.data_1;
var data2 = jsonData.data_2;
data.addRows([
[year, data1, data2]
]);
});
I'm trying to plot an annotation chart with google chart. However, I get the error "First column must be date or datetime". If I were to change the chart type to be area or line for example, it works fine.
Here's the javascript section of the "View page source" content of the final HTML page on which I'm expecting a graph to be drawn
<script type="text/javascript">
google.load('visualization', '1', {'packages':['annotationchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded FROM server.
var data_1 = google.visualization.arrayToDataTable([['ACTIVITY DATE TIME','ACTIVITY DURATION'],['2015-10-31 02:00:00',503],['2015-11-01 09:26:00',4],['2015-11-01 11:30:00',2],['2015-11-01 19:33:00',2],['2015-11-02 01:15:00',2],['2015-11-02 03:09:00',2],['2015-11-02 07:04:00',2],['2015-11-02 09:47:00',2],['2015-11-02 11:10:00',2]]);
var options = {
displayAnnotations: true
};
var chart_1 = new google.visualization.AnnotationChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
}
;
</script>
Could I request help please to figure out the problem? Is there any typecasting needed or anything whatsoever to get this working please?
UPDATED CODE
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['annotationchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded FROM server.
var data_1 = google.visualization.arrayToDataTable([<?php echo (implode(",", $chart_array_1)); ?>]);
var options = {
displayAnnotations: true
};
var chart_1 = new google.visualization.AnnotationChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
}
;
Yes, you have to cast those strings as Dates.
var data = [
['ACTIVITY DATE TIME', 'ACTIVITY DURATION'],
['2015-10-31 02:00:00', 503],
['2015-11-01 09:26:00', 4],
['2015-11-01 11:30:00', 2],
['2015-11-01 19:33:00', 2],
['2015-11-02 01:15:00', 2],
['2015-11-02 03:09:00', 2],
['2015-11-02 07:04:00', 2],
['2015-11-02 09:47:00', 2],
['2015-11-02 11:10:00', 2]
];
// or var data = [<?php echo (implode(",", $chart_array_1)); ?>]
for(var i = 1; i < data.length; i++)
data[i][0] = new Date(data[i][0]); // converting strings to Dates
google.load('visualization', '1', {
'packages': ['annotationchart']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded FROM server.
var data_1 = google.visualization.arrayToDataTable(data);
var options = {
displayAnnotations: true
};
var chart_1 = new google.visualization.AnnotationChart(document.getElementById('plot1'));
chart_1.draw(data_1, options);
};
JSFiddle
I create a chart with chart.js in PHP which looks like this:
$chart = <<<ECHO
<script type="text/javascript">
var ctx = document.getElementById("myChart").getContext("2d");
Chart.types.Bar.extend({
name: "myChart",
initialize: function () {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
}
});
new Chart(ctx).myChart(data, {
scaleLabel : "<%= value + ' $' %>"
});
</script>
ECHO;
echo $chart;
This code works fine if I run it in Javascript but unfortunately I need to display it via PHP (I use a component in a CMS) which doesnt work. I get the following error:
Parse error: syntax error, unexpected '=', expecting '}' in process.php(1227) : eval()'d code on line 154
I narrowed the error down to the initialize: function() {...} line of code. But why does it cause problems within the PHP echo?
I'm not sure why you're having problems, I don't think you should be.
But I have a better answer for you, use buffers instead of heredocs (they're easier to work with anyway)
Google ob_start to learn how it works, they're super useful
ob_start()?>
<script type="text/javascript">
var ctx = document.getElementById("myChart").getContext("2d");
Chart.types.Bar.extend({
name: "myChart",
initialize: function () {
Chart.types.Bar.prototype.initialize.apply(this, arguments);
}
});
new Chart(ctx).myChart(data, {
scaleLabel : "<%= value + ' $' %>"
});
</script>
<?php $chart = ob_get_clean();
echo $chart;
I have to visualize url json data on a pie chart with google visualization. My code seems to be as it has to be for the purpose, but I am getting an 'Invalid row type for row 0' error in the console. Is there any problem with the format of the data? If there is anyone that could help, that would be much appreciated. Here is my code:
PHP:
<?php
$json = file_get_contents('http://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2013-01');
$json = str_replace("\xe2\x80\xa8", '\\u2028', $json);
$json = str_replace("\xe2\x80\xa9", '\\u2029', $json);
echo $json;
?>
JavaScript:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
//Create an array of the JSON data and then create our data table out of JSON data loaded from server.
var array = JSON.parse(jsonData);
var dataTableData = new google.visualization.arrayToDataTable(array);
var table = google.visualization.DataTable(dataTableData);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
Thank you.
The JSON does not represent data which can be transformed to a 2-dimensional array google.visualization.DataTable can simply not interpret this. Each item contains complex subitems like location and outcome_status.
You must include columns - arrayToDataTable is very specific about that.
The most important : How on earth do you imagine those data to be presented as a piechart? There is only one specfic number-field at first level, location_subtype. You cannot produce a piechart based on various strings.
But, you can sanitize the data and show them as a google.visualization.Table :
First create a DataTable with some columns :
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string','category');
dataTable.addColumn('string','context');
dataTable.addColumn('string','id');
dataTable.addColumn('number','location_subtype');
dataTable.addColumn('string','location_type');
dataTable.addColumn('string','month');
dataTable.addColumn('string','persistent_id');
convert your jsonData to JSON
var json=JSON.parse(jsonData);
sanitize and insert the data. Here I just delete the location and outcome_status subitems, but you may want to extract values from those subitems instead and insert them as columns in the dataTable :
for (var i=0;i<json.length;i++) {
delete json[i].location;
delete json[i].outcome_status;
var row = [];
for (var item in json[i]) {
row.push(json[i][item]);
}
dataTable.addRow(row);
}
finally create the Table() :
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(dataTable, {width: 1000, height: 300});
the result will look like this :
update
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string','category');
dataTable.addColumn('string','context');
dataTable.addColumn('number','id');
dataTable.addColumn('string','location_subtype');
dataTable.addColumn('string','location_type');
dataTable.addColumn('string','month');
dataTable.addColumn('string','persistent_id');
dataTable.addColumn('string','street name');
dataTable.addColumn('string','outcome status');
json=JSON.parse(jsonData);
for (var i=0;i<json.length;i++) {
var row = [];
row.push(json[i].category);
row.push(json[i].context);
row.push(json[i].id);
row.push(json[i].location_subtype);
row.push(json[i].location_type);
row.push(json[i].month);
row.push(json[i].persistent_id);
row.push(json[i].location.street.name);
row.push(json[i].outcome_status ? json[i].outcome_status.category : "null");
dataTable.addRow(row);
}