Using timeline Google Chart API in PHP - Date/Time formatting issues - javascript

I am trying to implement Google's Timeline API
https://developers.google.com/chart/interactive/docs/gallery/timeline#controlling-the-colors
I am having issues with the date format as I am unsure of how to store/convert my time format to the correct format for the timeline chart.
My Database looks like this:
And I am trying to output a chart to look like this: (This is a hard coded example)
My current code looks like the following:
<?php
$connect=mysqli_connect("localhost","root","","smartcinema");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT a.screen_name, m.title, s.show_startime, s.show_endtime FROM timetable AS t INNER JOIN showing AS s ON s.showing_id = t.showing_id JOIN auditorium AS a ON a.screen_id = t.screen_id JOIN movies AS m ON m.movie_id = t.movie_id";
$qresult = mysqli_query($connect,$query);
$rows = array();
$table = array();
$table['cols'] = array (
array('id' => 'Screen', 'type' => 'string'),
array('id' => 'Movie', 'type' => 'string'),
array('id' => 'Start time', 'type' => 'date'),
array('id' => 'End time', 'type' => 'date')
);
while($res = mysqli_fetch_assoc($qresult)){
$result[] = $res;
}
foreach ($result as $r) {
$temp = array();
$temp[] = array('v' => $r['screen_name']);
$temp[] = array('v' => $r['title']);
$temp[] = array('v' => 'new Date(0,0,0,'.date('H',strtotime($r['show_startime'])).','.date('i',strtotime($r['show_startime'])).','.date('s',strtotime($r['show_startime'])).')');
$temp[] = array('v' => 'new Date(0,0,0,'.date('H',strtotime($r['show_endtime'])).','.date('i',strtotime($r['show_endtime'])).','.date('s',strtotime($r['show_endtime'])).')');
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
print_r($jsonTable);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["timeline"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var container = document.getElementById('test');
var chart = new google.visualization.Timeline(container);
var options = {
timeline: { colorByRowLabel: true },
backgroundColor: '#ffd'
};
chart.draw(dataTable, options);
}
</script>
<div id="test" ></div>

When you print_r($jsonTable); -- how does it differ from the following example?
google.charts.load('current', {
callback: drawChart,
packages: ['timeline']
});
function drawChart() {
var dataTable = new google.visualization.DataTable({
cols: [
{id: 'Screen', type: 'string'},
{id: 'Movie', type: 'string'},
{id: 'Start time', type: 'date'},
{id: 'End time', type: 'date'}
],
rows: [
{c:[{v: 'Screen 1'}, {v: 'Batman v Superman: Dawn of Justice'}, {v: new Date(0, 0, 0, 10, 0, 0)}, {v: new Date(0, 0, 0, 12, 31, 0)}]},
{c:[{v: 'Screen 1'}, {v: 'Batman v Superman: Dawn of Justice'}, {v: new Date(0, 0, 0, 12, 51, 0)}, {v: new Date(0, 0, 0, 15, 22, 0)}]},
{c:[{v: 'Screen 1'}, {v: 'Batman v Superman: Dawn of Justice'}, {v: new Date(0, 0, 0, 15, 42, 0)}, {v: new Date(0, 0, 0, 18, 13, 0)}]},
{c:[{v: 'Screen 2'}, {v: 'High-Rise'}, {v: new Date(0, 0, 0, 10, 0, 0)}, {v: new Date(0, 0, 0, 11, 52, 0)}]},
{c:[{v: 'Screen 2'}, {v: 'High-Rise'}, {v: new Date(0, 0, 0, 12, 2, 0)}, {v: new Date(0, 0, 0, 13, 54, 0)}]},
{c:[{v: 'Screen 2'}, {v: 'High-Rise'}, {v: new Date(0, 0, 0, 14, 4, 0)}, {v: new Date(0, 0, 0, 15, 56, 0)}]},
]
});
var container = document.getElementById('example');
var chart = new google.visualization.Timeline(container);
chart.draw(dataTable);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="example"></div>

So I was looking back over my code and instead of defining:
var dataTable = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
I was defining
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
The variable name i was defining was incorrect so my working code is now :
<?php
$connect=mysqli_connect("localhost","root","","smartcinema");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT a.screen_name, m.title, s.show_startime, s.show_endtime FROM timetable AS t INNER JOIN showing AS s ON s.showing_id = t.showing_id JOIN auditorium AS a ON a.screen_id = t.screen_id JOIN movies AS m ON m.movie_id = t.movie_id";
$qresult = mysqli_query($connect,$query);
$rows = array();
$table = array();
$table['cols'] = array (
array('id' => 'Screen', 'type' => 'string'),
array('id' => 'Movie', 'type' => 'string'),
array('id' => 'Start time', 'type' => 'date'),
array('id' => 'End time', 'type' => 'date')
);
while($res = mysqli_fetch_assoc($qresult)){
$result[] = $res;
}
foreach ($result as $r) {
$temp = array();
$temp[] = array('v' => $r['screen_name']);
$temp[] = array('v' => $r['title']);
$temp[] = array('v' => 'Date(0,0,0,'.date('H',strtotime($r['show_startime'])).','.date('i',strtotime($r['show_startime'])).','.date('s',strtotime($r['show_startime'])).')');
$temp[] = array('v' => 'Date(0,0,0,'.date('H',strtotime($r['show_endtime'])).','.date('i',strtotime($r['show_endtime'])).','.date('s',strtotime($r['show_endtime'])).')');
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
callback: drawChart,
packages: ['timeline']
});
function drawChart() {
var dataTable = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var container = document.getElementById('example');
var chart = new google.visualization.Timeline(container);
chart.draw(dataTable);
}
</script>
<div id="example" ></div>

Related

Fetching data from SQL database and using it in vis.js Timeline group order chart

I am trying to build a vis.js based timeline group order chart in a web page and giving it a database connectivity. I am able to display the chart in a web page and give it database connectivity. However, I am not sure how to pass the data in vis.dataset().
below is my code:
Connection.php
<?php
$sname = "localhost";
$uname = "postgres";
$pass = "123456";
$db_name = "apple";
// Connection with database
try
{
$conn = new PDO("pgsql:host=$sname;dbname=$db_name", $uname, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "connected";
// Checking the database connection by Querying the table
$dbconn = $conn->query("SELECT * FROM \"pgdataset\" ORDER by id ASC");
while($result = $dbconn->fetch(PDO::FETCH_ASSOC))
{
$finalresult = json_encode($result);
echo "$finalresult";
}
}
catch(PDOException $e)
{
echo "connection failed:". $e->getMessage();
}
<div id="visualization"></div>
<script type="text/javascript">
var groups = new vis.DataSet($finalresult);
// create a dataset with items
var items = new vis.DataSet([
{
id: 1,
group: 1,
start: new Date(2014, 3, 17, 14, 4, 0),
end: new Date(2014, 3, 17, 15, 15, 0),
},
{
id: 2,
group: 1,
start: new Date(2014, 3, 17, 05, 40, 0),
end: new Date(2014, 3, 17, 06, 04, 0),
},
{
id: 3,
group: 2,
start: new Date(2014, 3, 17, 11, 02, 0),
end: new Date(2014, 3, 17, 12, 10, 0),
},
]);
// create visualization
var container = document.getElementById("visualization");
var options = {
groupOrder: function (a, b) {
return a.value - b.value;
},
};
var timeline = new vis.Timeline(container);
timeline.setOptions(options);
timeline.setGroups(groups);
timeline.setItems(items);
}
});
</script>

google charts timeline - cannot read property length of null

Following there are 2 examples of google charts code. The only difference in the last example is the start second. Does anybody know, why I get "cannot read property 'length' of null" in the last example? Also if I shorten the name of row 2 and 3 from "Second Test entry number 2" to a shorter, the chart is displayed.
Working: https://jsfiddle.net/5rotomyc/
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Group' });
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
['First', null, new Date(2017,1,15, 22, 40, 27), new Date(2017,10,29, 23, 59, 59)],
['Second Test entry number 2', null, new Date(2017,8,4, 0, 0, 0), new Date(2018,0,16, 23, 59, 59)],
['Second Test entry number 2', null, new Date(2018,0,25, 0, 0, 0), new Date(2018,1,06, 23, 59, 59)]
]);
chart.draw(dataTable);
}
Second example which is not working https://jsfiddle.net/ypz095g9/:
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Group' });
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
['First', null, new Date(2017,1,15, 22, 40, 26), new Date(2017,10,29, 23, 59, 59)],
['Second Test entry number 2', null, new Date(2017,8,4, 0, 0, 0), new Date(2018,0,16, 23, 59, 59)],
['Second Test entry number 2', null, new Date(2018,0,25, 0, 0, 0), new Date(2018,1,06, 23, 59, 59)]
]);
chart.draw(dataTable);
}
I'm getting desperate right here. hope somebody can help with this bug. Thank you.
looks like a problem with addRows
seen weird stuff happen when an entire column only has null values
(the code actually works for me as-is in chrome)
the 'Role' column is optional, you can remove it...
see following working snippet...
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Group' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
['First', new Date(2017,1,15, 22, 40, 26), new Date(2017,10,29, 23, 59, 59)],
['Second Test entry number 2', new Date(2017,8,4, 0, 0, 0), new Date(2018,0,16, 23, 59, 59)],
['Second Test entry number 2', new Date(2018,0,25, 0, 0, 0), new Date(2018,1,06, 23, 59, 59)]
]);
chart.draw(dataTable);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>
or use a blank string '' instead...
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Group' });
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
['First', '', new Date(2017,1,15, 22, 40, 26), new Date(2017,10,29, 23, 59, 59)],
['Second Test entry number 2', '', new Date(2017,8,4, 0, 0, 0), new Date(2018,0,16, 23, 59, 59)],
['Second Test entry number 2', '', new Date(2018,0,25, 0, 0, 0), new Date(2018,1,06, 23, 59, 59)]
]);
chart.draw(dataTable);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="timeline"></div>

highchart.js is not working. error 13

This is the image of the error:
This error 13 is always showing up. I just cannot find the reason why highchart.js is not working. Can anyone help me to fix this one? Thanks
<?php
$q = $this->db->query("select * from scli_tbl_services");
foreach ($q->result() as $row) {
$data[] = $row->service_id;
}
?>
<script type="text/javascript">
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart_sample'
},
series: [{
data: [<?php echo join($data, ',') ?>],
pointStart: 0,
pointInterval: 10
}]
});
</script>
<span id="chart_sample" class="chart_sample"></span>
This is my code that I'm about to run. So I don't know if my code also is working fine.
HighChart.Js Solution :
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>
<?php
$newArray = array(
"Valvo" => Array(10,15,20),
"ACBUS" => Array(25,30,15),
"SchoolBus" => Array(25,30,15),
"MiniBus" => Array(25,30,15),
"CityBus" => Array(25,30,15)
);
$json_array_form = array();
$data = '';
foreach ($newArray as $key => $value){
$json_array_form['name'] = $key;
$json_array_form['data'] = $value;
$data .= json_encode($json_array_form).',';
}
$data = substr($data, 0, -1);
?>
//HighChart Js functionality start
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [<?php echo $data;?>],
});
});
</script>

Google Timeline fix different color for each timesheets

I have a timeline with a lot of rows and in each rows are several timesheets.
I would like to fix for each timesheet an exact color, so one type of timesheet will have same color in every row.
I am using this code:
var options = {
colors: ['#0C14F2', '#114C9E', '#ee8800', '#F6FF00'],
timeline: {
showBarLabels: false,
avoidOverlappingGridLines: false
},
backgroundColor: '#f8f8ff'
};
This code changes the colors seemly randomly of timesheets.
UPDATE: Sample JSON output
{"cols":[{"label":"Name","type":"string"},{"label":"Description","type":"string"},{"label":"Start","type":"date"},{"label":"End","type":"date"},{"role":"style","type":"string"}],"rows":
[{"c":[{"v":"Sample Name"},{"v":"Sample Desc"},{"v":"Date(2014,09,09,0,0,0)"},{"v":"Date(2014,09,09,1,0,0)"},{"v":"#124T‌​9E"}]},
Using the "colors" option is not the best approach, as the process for setting this option correctly to get the colors you want is rather complex. A much simpler way to do this is to use a "style" role column that has the desired color for the bar listed directly in it, eg:
var data = google.visualization.arrayToDataTable([
['Category', 'Name', {role: 'style'}, 'Start', 'End'],
['Foo', 'Cad', '#a23c7a', new Date(2014, 7, 1), new Date(2014, 7, 5)],
['Foo', 'Qud', '#40a67d', new Date(2014, 7, 3), new Date(2014, 7, 4)],
['Bar', 'Fiz', '#5581b4', new Date(2014, 7, 2), new Date(2014, 7, 9)]
]);
see example: http://jsfiddle.net/asgallant/qgo310pc/1/
[Edit in response to comments]
You can create the column in PHP like this:
$table = array(
'cols' => array(
array('label' => 'Name', 'type' => 'string'),
array('label' => 'Description', 'type' => 'string'),
array('role' => 'style', 'type' => 'string'),
array('label' => 'Start', 'type' => 'date'),
array('label' => 'End', 'type' => 'date')
)
);

Google chart timeline with date in x axis

Working on a google line chart. The problem I have came into is that the chart on shows values of one day, have not implemented timeline with dates. I understand that the chart will be wide if your getting values from for example one week, is there any way to solve that ? I was thinking of something like this ?
How its looking right now:
Database: ( the date is saved as date in phpadmin)
Code:
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysql_select_db("chart", $con);
$sth = mysql_query("SELECT * FROM googlechart");
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'Time', 'type' => 'number'),
array('label' => 'PH', 'type' => 'number'),
array('label' => 'temperature','type' => 'number'),
array('label' => 'Chlorine','type' => 'number'),
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Time']);
$temp[] = array('v' => (string) $r['PH']);
$temp[] = array('v' => (string) $r['temperature']);
$temp[] = array('v' => (string) $r['Chlorine']);
$temp[] = array('v' => (int) $r['Time']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>
<html>
<head>
<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(<?=$jsonTable?>);
var options = {
/*width: 900, height: 900, */
title: 'Visualization',
/* curveType: 'function', */
legend: { position: 'bottom' },
pointSize: 10,
vAxis: {title: "Values", titleTextStyle: {italic: false}},
hAxis: {title: "Time", titleTextStyle: {italic: false}},
};
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>
You can get part of what you want using format property of hAxis, for example:
hAxis: {
format: "HH:mm",
...
}
See line chart configuration options for hAxis.format.
Update: Example at jsbin

Categories