Google Charts Timeline - PHP array as input - javascript

I am working on a Google Charts Timeline plot, showing the duration periods of a number of tasks, located in a table in a MySQL database. Using PHP there is a number of ways to retrieve and store this, for instance as a 2-dimensional array. However, is there a way to pass such an array (or other easily created data containing objects), in the way that the Google Charts Timeline can handle, through the dataTable.addrows() method?
Or if I should describe it as an example:
function drawChart() {
// Nothing to see here, move along now...
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
// The column heading can be fixed or variable, this doesnt matter.
dataTable.addColumn({ type: 'string', id: 'Opgave ID' });
dataTable.addColumn({ type: 'string', id: 'Opgavetitel' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
/* I would like to replace the fixed input of dataTable.addRows, with a
*variable input, for instance a 2-dimensional PHP-array.
*/
dataTable.addRows([
[ '1', 'Some task', new Date(2015, 3, 9), new Date(2015, 3, 23) ],
[ '2', 'Another task', new Date(2015, 3, 13), new Date(2015, 3, 20) ],
[ '3', 'A different task', new Date(2015, 3, 16), new Date(2015, 3, 30) ]]);
// No questions for any of this
var options = {
timeline: {showRowLabels: false, singleColor: '#8d8'}
};
chart.draw(dataTable, options);
}

Doing a quick google search, I found this article:
http://www.dyn-web.com/tutorials/php-js/json/multidim-arrays.php
I'm not a PHP programmer, so this isn't tested but should work:
<?
$timeData = array(
array('1', 'Some task', new DateTime('2015-04-09'), new DateTime('2015-04-23')),
array('2', 'Another task', new DateTime('2015-04-13'), new DateTime('2015-04-20')),
array('3', 'A different task', new DateTime('2015-04-16'), new Date('2015-04-30))
);
?>
function drawChart() {
// Nothing to see here, move along now...
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
// The column heading can be fixed or variable, this doesnt matter.
dataTable.addColumn({ type: 'string', id: 'Opgave ID' });
dataTable.addColumn({ type: 'string', id: 'Opgavetitel' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows(<? echo json_encode( $timeData ); ?>);
// No questions for any of this
var options = {
timeline: {showRowLabels: false, singleColor: '#8d8'}
};
chart.draw(dataTable, options);
}
You may find it easier to locate existing material if you broaden your search to a more basic concept (passing a PHP 2d array to javascript). Here's an example of an existing Stack Overflow question on that topic:
Best way to pass a 2d array into JavaScript from PHP?
And there are many more like it.

I got the same problem while using Google Charts Timeline while using Laravel 6.0 framework. I passed the query results to the view file as an associative array and the used json_encode() to convert the associative array into a JavaScript array that turned into an array of objects:
<script>
// create a custom data object to pass into the array
// the charter array data is of the format:
//
// Array(5)
// 0: {mn: "2020-02-12 10:03:17", mx: "2022-07-12 10:03:17", cha_booking_id: 1}
// 1: {mn: "2020-02-12 13:33:07", mx: "2020-10-12 13:33:07", cha_booking_id: 2}
// 2: {mn: "2020-02-12 13:39:47", mx: "2020-08-12 13:39:47", cha_booking_id: 3}
// 3: {mn: "2020-04-12 06:21:08", mx: "2020-04-12 06:21:08", cha_booking_id: 4}
// 4: {mn: "2020-05-12 08:44:24", mx: "2020-07-12 08:44:24", cha_booking_id: 5}
var data = [];
charter.forEach(el => {
var arr = [
el.cha_booking_id.toString(),
new Date(
el.mn.substring(0, 4), // get the year from the date format that is passed
el.mn.substring(5, 7), // get the month from the date format that is passed
el.mn.substring(8, 10) // get the day from the date format that is passed
),
new Date(
el.mx.substring(0, 4),
el.mx.substring(5, 7),
el.mx.substring(8, 10)
)
];
data.push(arr);
// The column heading can be fixed or variable, this doesnt matter.
dataTable.addColumn({ type: 'string', id: 'Opgave ID' });
dataTable.addColumn({ type: 'string', id: 'Opgavetitel' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows(data);
// No questions for any of this
var options = {
timeline: {showRowLabels: false, singleColor: '#8d8'}
};
chart.draw(dataTable, options);
</script>

Related

Pass google script variable/array to HTML

I'm building a web app that is google's chart Timeline. I have a script that returns me the correct array from google sheets. I want to pass this result to HTML in a specific place. I'm using google app scripts.
function doGet(e) {
return HtmlService.createTemplateFromFile('timeline3').evaluate();
}
function useDataRange() {
var rows = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
var test = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getRange(3, 7, rows.getLastRow(), 1).getValues();
test = test.slice(0,rows.getLastRow()-2);
JSON.stringify(test);
Logger.log(test);
return test;
}
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script type="text/javascript">
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(getData);
function getData(){
return google.script.run.withSuccessHandler(drawChart).useDataRange();
}
function drawChart(arrayFromSheets) {
var container = document.getElementById('timeline-tooltip');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'President' });
dataTable.addColumn({ type: 'string', id: 'dummy bar label' });
dataTable.addColumn({ type: 'string', role: 'tooltip' });
dataTable.addColumn({ type: 'string', id: 'style', role: 'style' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows(arrayFromSheets);
chart.draw(dataTable);
}
</script>
<div id="timeline-tooltip" style="height: 400px;"></div>
</body>
</html>
I'm trying to populate dataTable.addRows() with my array. I've looked through google's documentation and this should work. I just don't get it. Please help
Here is an example of array I get returned from useDataRange function:
[['Lady Gita' ,null , 'June 19 -26' , '#176BEF', new Date(2021, 6, 19) , new Date(2021, 6, 26)], ['Lady Gita' ,null , 'Jun 27 - Jul 11' , '#FF3E30', new Date(2021, 6, 27) , new Date(2021, 7, 11)]]
Searching in console I get this:
Console:
Why not just var test = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getRange(3, 7, rows.getLastRow()-2, 1).getValues(); The third param is number of rows not last row
Arrays weren't being passed as arrays because I had a function inside them. They were all being passed as undefined. I had to change a bit my sheet but it works now. Also null was showing as BarLabel so I turned BarLabel off with options. It works great now!
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<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(getData);
function getData(){
google.script.run.withSuccessHandler(drawChart).useDataRange();
}
function drawChart(data) {
var container = document.getElementById('timeline-tooltip');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'President'});
dataTable.addColumn({ type: 'string', id: 'dummy bar label'});
dataTable.addColumn({ type: 'string', role: 'tooltip'});
dataTable.addColumn({ type: 'string', id: 'style', role: 'style'});
dataTable.addColumn({ type: 'date', id: 'Start'});
dataTable.addColumn({ type: 'date', id: 'End'});
var rows = [];
//Loop through the data you loaded and push it to the rows array
for(var i=0; i<data.length; i++){
var currentElement = data[i];
var transformFirstDate = new Date(currentElement[4]);
var transformSecondDate = new Date(currentElement[5]);
rows.push([currentElement[0],currentElement[1],currentElement[2],currentElement[3],transformFirstDate,transformSecondDate]);
}
dataTable.addRows(rows);
var options = {
timeline: { showBarLabels: false }
};
chart.draw(dataTable, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="timeline-tooltip" style="height: 400px;"></div>
</body>
</html>

Using Years Only (Without Months or Days) with Google Timeline Charts

I want to show a timeline (with Google Charts) with years only.
However, the examples on Google Charts Timelines' webpage always comprise years, months and days (for instance, new Date(1789, 3, 30)).
I have tried reducing the new Date() to just a year (e.g. new Date(2019)), but Google Charts interprets it as seconds (2.019 seconds).
<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 container = document.getElementById('div_timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Nr' });
dataTable.addColumn({ type: 'string', id: 'Journal' });
dataTable.addColumn({ type: 'date', id: 'Founded' });
dataTable.addColumn({ type: 'date', id: 'Now' });
dataTable.addRows([
[ '1', 'Journal of Leisure Research', new Date(1969), new Date(2019) ],
[ '2', 'Critical Sociology', new Date(2009), new Date(2019) ],
[ '3', 'Geographical Analysis', new Date(1909), new Date(2019) ]
]);
chart.draw(dataTable,options);
}
</script>
With this code, Journal of Leisure Research is now 1.969 seconds to 2.019 seconds.
Instead, I want the chart to assign the years 1969 to 2019.
How can I do that? Thanks for your help!
Simply set the date to January 1st:
<html>
<head>
<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 container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Nr' });
dataTable.addColumn({ type: 'string', id: 'Journal' });
dataTable.addColumn({ type: 'date', id: 'Founded' });
dataTable.addColumn({ type: 'date', id: 'Now' });
dataTable.addRows([
[ '1', 'Journal of Leisure Research', new Date(1969,1,0), new Date(2019,1,0) ],
[ '2', 'Critical Sociology', new Date(2009,1,0), new Date(2019,1,0) ],
[ '3', 'Geographical Analysis', new Date(1909,1,0), new Date(2019,1,0) ]]);
chart.draw(dataTable);
}
</script>
</head>
<body>
<div id="timeline" style="height: 180px;"></div>
</body>
</html>

Dummy rows for Google Charts Timelines?

I'm looking for a way to add a dummy row to Google Charts Timelines. Here is what I'm trying to accomplish:
However, the dummy row should be transparent and should not have interactivity (no tooltip, no select event, etc.).
Here is my workaround:
This requires adding three more columns and you lose the tooltip generated by Charts. While this isn't an issue for me (as I will be customizing the tooltips), it may be for others. Furthermore, although the dummy row is transparent, there is still interactivity (as indicated by the empty tooltip I circled). The workaround for this is to add the following code immediately before chart.draw(dataTable):
function onMouseOver(e) {
var tooltips = document.getElementsByClassName('google-visualization-tooltip');
for (var i = 0; i < tooltips.length; i++) {
if (!tooltips[i].innerHTML) {
tooltips[i].style.display = 'none';
}
}
}
function onReady() {
google.visualization.events.addListener(chart, 'onmouseover', onMouseOver);
}
google.visualization.events.addListener(chart, 'ready', onReady);
While this is technically a solution to my problem, it's a hack at best. Is there no straightforward way to accomplish this with the API?
This is already a year old question, but maybe someone else will have the same problem. Your solution from second screen was very close. You need to set tooltip value on normal rows to null (will display standard tooltip) and empty string on dummy items (tooltip will be hidden). The style column must have opacity set to 0 on dummy rows to hide the bar. Below is rewritten and fixed code from your example.
google.charts.load('current', { packages: ['timeline']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
const container = document.getElementById('timeline');
const chart = new google.visualization.Timeline(container);
const dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', label: 'President', id: 'President' });
dataTable.addColumn({ type: 'string', id: 'Empty label' });
dataTable.addColumn({ type: 'string', id: 'style', role: 'style' });
dataTable.addColumn({ type: 'string', id: 'tooltip', role: 'tooltip', p: { html: true } });
dataTable.addColumn({ type: 'date', label: 'Start', id: 'Start' });
dataTable.addColumn({ type: 'date', label: 'End', id: 'End' });
dataTable.addRows([
['A', '', 'opacity: 0', '', new Date('2018-06-05T00:00:00'), new Date('2018-06-05T00:00:00')],
['B', '', 'opacity: 0', '', new Date('2018-06-05T00:00:00'), new Date('2018-06-05T00:00:00')],
['C', '', 'opacity: 0', '', new Date('2018-06-05T00:00:00'), new Date('2018-06-05T00:00:00')],
['A', '', null, null, new Date('2018-06-05T01:00:00'), new Date('2018-06-05T02:00:00')],
['B', '', null, null, new Date('2018-06-05T01:00:00'), new Date('2018-06-05T02:00:00')],
['C', '', null, null, new Date('2018-06-05T01:00:00'), new Date('2018-06-05T02:00:00')],
]);
}
After tackling with this problem I prefer to use apexcharts package for timeline chart creating. This package has more flexible interface to control the charts, min and max values of axis, tooltips, etc.

Set null dates on Google Chart Timeline

Im trying to create a Timeline chart using Google Chart API. However the problem is I can't handle null dates on specific rows.
How do you hide rows that have null Start or End dates?
google.charts.load("current", {packages:["timeline"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('timeline');
var chart = new google.visualization.Timeline(container);
google.visualization.events.addListener(chart, 'error', errorHandler);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[
'NTC',
'NTC',
new Date('07/05/2016'),
new Date('07/06/2016'),
],
[
'Briefing Meeting',
'Baseline',
new Date('07/07/2016'),
new Date('07/06/2016'),
],
[
'Concept Design',
'Baseline',
new Date('07/05/2016'),
new Date('07/06/2016'),
],
[
'Concept Design',
'Forecast',
new Date('07/05/2016'),
new Date('07/06/2016'),
],
[
'Concept Design',
'Actual',
new Date('07/05/2016'),
new Date('07/06/2016'),
],
[
'Detail Design',
'Baseline',
new Date('07/05/2016'),
new Date('07/06/2016'),
],
[
'Detail Design',
'Forecast',
new Date('07/05/2016'),
new Date('07/06/2016'),
],
[
'Detail Design',
'Actual',
new Date('07/05/2016'),
new Date(),
],
]);
var colors = [];
var colorMap = {
Baseline: '#425cfb',
Forecast: '#f8ac08',
Actual: '#06af90',
NTC: '#1b9e2e'
}
for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
colors.push(colorMap[dataTable.getValue(i, 1)]);
}
var options = {
colors: colors,
timeline: {
showBarLabels: false,
groupByRowLabel: true,
// rowLabelStyle: {fontName: 'Helvetica', fontSize: 24, color: '#603913'},
barLabelStyle: { fontName: 'Garamond', fontSize: 6 },
},
interpolateNulls: true,
};
}
It displays invalid datetime if I set new Date(0), Is there a workaround here?
Filtering the already incorrect rows when you have the possibility to filter these posts at your server code is a waste of time and resources. Try to filter these in your PHP instead!
Google provides you with a filter method which you can use to filter your rows. I've also used the DataView class in this solution.
First I created a filterDate at the same time as the rest of our empty new Date()s, then I 'zeroed' the milliseconds, as there might pass a millisecond or two before this is executed.
//use this one to determine what date to filter away.
var filterDate = new Date();
filterDate.setMilliseconds(0);
//Convert to JSON
filterDate = filterDate.toJSON();
Then I filter the rows I wish to use, using the filter option test which executes a function, passing the value, row, column and datatable as parameters. Should return false if you wish to exclude the row:
//filter the rows we actually want
var someRows = dataTable.getFilteredRows([{
column: 2,
test: testFunc
}, {
column: 3,
test: testFunc
}]);
In our function that we call, testFunc we 'zero' the milliseconds, and convert it to JSON and then compare to our filterDate. If it's the same, we judge that the row should be excluded:
//This is our test function
function testFunc(value) {
value.setMilliseconds(0);
return value.toJSON() !== filterDate;
}
Lastly we initiate a DataView from our dataTable and we set our rows to be the ones we just filtered:
//Create a dataView object from our dataTable, and set the rows to the ones we just filtered
var dataView = new google.visualization.DataView(dataTable);
dataView.setRows(someRows);
And we're good to go, but as already stated, you should try to filter these at your serverside instead.
JSFiddle for reference

Google Timeline Chart: Color each bar individually when multiple on "same" line

The Google Timeline charts seem to suggest coloring individual blocks on the timeline per the documentation:
https://google-developers.appspot.com/chart/interactive/docs/gallery/timeline#ControllingColors
But there seems to be a problem when two bars "overlap" on the same line, as you can see in this fiddle:
http://jsfiddle.net/7A88H/21/
Here is the key code:
dataTable.addRows([
[ 'red/green/blue', 'NAME OF BAR (should be RED) (ff0000)', new Date(1789, 3, 29), new Date(1797, 2, 3) ],
[ 'red/green/blue', 'NAME OF BAR (should be GREEN) (00ff00)', new Date(1796, 2, 3), new Date(1801, 2, 3) ],
[ 'red/green/blue', 'NAME OF BAR (should be BLUE) (0000ff)', new Date(1801, 2, 3), new Date(1809, 2, 3) ]]);
var options = {
colors: ['#ff0000', '#00ff00', '#0000ff'],
};
I tried playing with the accepted answer from this question by adding a 5th column (the color) to my data rows:
Google Charts API: Add Blank Row to Timeline?
Specifically, here is the function I thought I might be able to hijack to build my hack:
(function(){ //anonymous self calling function to prevent variable name conficts
var el=container.getElementsByTagName("rect"); //get all the descendant rect element inside the container
var width=100000000; //set a large initial value to width
var elToRem=[]; //element would be added to this array for removal
for(var i=0;i<el.length;i++){ //looping over all the rect element of container
var cwidth=parseInt(el[i].getAttribute("width"));//getting the width of ith element
if(cwidth<width){ //if current element width is less than previous width then this is min. width and ith element should be removed
elToRem=[el[i]];
width=cwidth; //setting the width with min width
}
else if(cwidth==width){ //if current element width is equal to previous width then more that one element would be removed
elToRem.push(el[i]);
}
}
for(var i=0;i<elToRem.length;i++)
elToRem[i].setAttribute("fill","none"); //make invisible all the rect element which has minimum width
})();
The hope was to grab each rect (skipping the bounding ones) and filling them (with a third loop, at the end) with their appropriate colors, but I couldn't figure out how to get their associated color (which was in the row objects) from the rect objects themselves.
I think you will need to use the additional options:
timeline: { groupByRowLabel: false }
Because, if you go to the g-page: https://google-developers.appspot.com/chart/interactive/docs/gallery/timeline#BarsOneRow in the Bars in One Row section they show how Presidents DON'T overlap, so you can't use it in this case, but for the method you are using it, timelines do overlap so they must be in their own row. It would probably be hard to read overlapping titles anyhow.
Side note: I noticed what google is doing. It's assigning the colors left to right, then wrapping. The titles however, are not wrapping, they just go left to right. Here is a fiddle I made: https://jsfiddle.net/camp185/2Lopnnt3/2/ to show how wrapping of colors working...added more colors.
function drawChart() {
var container = document.getElementById('example5.4');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'red/green/blue', 'NAME OF BAR (should be RED) (ff0000)', new Date(1789, 3, 29), new Date(1797, 2, 3) ],
[ 'red/green/blue', 'NAME OF BAR (should be GREEN) (00ff00)', new Date(1796, 2, 3), new Date(1801, 2, 3) ],
[ 'red/green/blue', 'NAME OF BAR (should be BLUE) (0000ff)', new Date(1801, 2, 3), new Date(1809, 2, 3) ]]);
var options = {
colors: ['#ff0000', '#00ff00', '#0000ff'],
timeline: { groupByRowLabel: false }
};
chart.draw(dataTable, options);
}
google.load('visualization', '1', {packages:['timeline'], callback: drawChart});
<script src="https://www.google.com/jsapi?.js"></script>
<div id='example5.4'></div>
Hope this will help you:
google.load("visualization", "1", {packages:["timeline"]});
google.setOnLoadCallback(drawChart);
// google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('example5.4');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'red/green/blue', 'NAME OF BAR (should be RED) (ff0000)', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
[ 'red/green/blue', 'NAME OF BAR (should be GREEN) (00ff00)', new Date(1797, 2, 4), new Date(1801, 2, 4) ],
[ 'red/green/blue', 'NAME OF BAR (should be BLUE) (0000ff)', new Date(1801, 2, 4), new Date(1809, 2, 4) ]
]);
// dataTable.addRows([
// [ 'red/green/blue', 'NAME OF BAR (should be RED) (ff0000)', new Date(1789, 3, 29), new Date(1797, 2, 3) ],
// [ 'red/green/blue', 'NAME OF BAR (should be GREEN) (00ff00)', new Date(1796, 2, 3), new Date(1801, 2, 3) ],
// [ 'red/green/blue', 'NAME OF BAR (should be BLUE) (0000ff)', new Date(1801, 2, 3), new Date(1809, 2, 3) ]]);
var options = {
colors: ['#ff0000', '#00ff00', '#0000ff'],
};
chart.draw(dataTable, options);
}
<script src="https://www.google.com/jsapi?.js"></script>
<div id='example5.4'></div>
There are two ways to do what you want, both of which change the background color based on the title you give the row. With your current code, when you hover over one of the rows, it displays information about that row. However, when leaving the hover, it redraws the box, making it much more complicated. I have done it both ways for you:
JSFiddle with Interactivity disabled (much simpler.. unfortunately I did this one after I did the complicated one)
JSFiddle with Interactivity enabled and messy setTimeOut functions (doesn't always work)
Here's the code when interactivity is disabled:
function drawChart() {
var container = document.getElementById('example5.4');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Role' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'red/green/blue', 'SHORT TEXT GREEN(00ff00)', new Date(1796, 2, 3), new Date(1801, 2, 3) ],
[ 'red/green/blue', 'NAME OF BAR (should be BLUE) (0000ff)', new Date(1801, 2, 3), new Date(1809, 2, 3) ],
[ 'red/green/blue', 'NAME OF BAR (should be RED) (ff0000)', new Date(1789, 3, 29), new Date(1797, 2, 3) ]]);
// dataTable.addRows([]);
var options = {
colors: ['#000', '#000', '#000'], // assign black background to each row
enableInteractivity: false //interactivity disabled
};
chart.draw(dataTable, options);
var elements = document.getElementsByTagName("text");
for(var el in elements)
{
if(typeof colorArray[elements[el].innerHTML] != "undefined")
{
setColor(elements[el],colorArray[elements[el].innerHTML]);
}
}
}
google.load('visualization', '1', {packages:['timeline'], callback: drawChart});
var colorArray = []; // format: colorArray["TEXT IN ROW"] = "COLOR"
colorArray["NAME OF BAR (should be RED) (ff0000)"] = "#ff0000";
function setColor(elem,newColor)
{
var rect = elem.previousSibling;
var rTitle = rect.innerHTML;
rect.setAttribute("fill",newColor);
}
NOTE: if the page is too narrow and text in a row is shortened with an ellipsis (...), this method fails because it is based off of the text in each row.
-- Old answer with no hack --
After looking into it further, it appears a simple way to fix this is by shortening the text of the green bar, because even when adding a new, separate row, the text for the green box doesn't fit inside of the box.
Additionally, it is processing the colors by line, so the Blue bar is getting the green color since the Green bar is being pushed to a new line. I would add any rows that will make a new line in a separate statement just to make it map out more logically, although it doesn't make a difference what order the arrays are in.
Here's the JSFiddle

Categories

Resources