Add a Timeline to Your Website with Google Charts

Share this article

To grab a reader’s attention, it is a good idea to display your datasets in the form of charts instead of tables. If you are talking about a lot of events on your blog, displaying those events in a chronological order on a timeline will communicate the message in a more effective and interesting manner.

In this tutorial, I’ll teach you how to use Google Charts to add professional looking timelines to your web pages.

Key Takeaways

  • Google Charts can be used to create professional looking timelines on web pages, making data more engaging and easier to digest for readers.
  • The Google Charts API requires an HTML element to draw its charts, and data to be represented in a DataTable with columns and rows representing the timeline’s data.
  • The appearance of the timeline can be customized by creating a JSON object that contains properties and preferred values. This can include changes to the background color and color of the timeline bars.
  • Google Charts allows for interactivity, such as tooltips that appear when hovering over an item on the chart, and custom behavior when a data item is clicked on.

Loading Google Charts

Since I’m going to make use of Google API Loader to load Google Charts, I’ll add the following script tag to the header of the page that’s going to display the timeline:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

I can now use the google.load method to load any Google API. For Google Charts, I’ll need to load the Visualization API along with the timeline package of the API. I’ll also add a callback to know when the API is ready.

google.load('visualization', '1.0', { packages:["timeline"] });
google.setOnLoadCallback(start);

function start() {
  /* This method will be called when the
     Visualization API has been loaded. */
}

Adding an Element to Hold the Chart

The Charts API needs an HTML element to draw its charts. I’ll add an empty div to the body of the page and call it timelineHolder. I can set the dimensions of your timeline by setting the width and height properties of in the CSS. Let’s create a timeline with dimensions of 600px x 300px.

.timelineHolder {
  width: 600px;
  height: 300px;
}

Defining the Timeline’s Data

For this tutorial, let us represent a year in the life of an imaginary traveler, named Alice, on a timeline. Here’s what Alice did that year:

  • From January 15 to February 26 she was in Berlin
  • From April 20 to July 1 she was in Paris
  • From July 21 to August 30 she was in Madrid
  • From November 2 to December 5 she was in Perth

This information has to be converted into a DataTable. Our DataTable is going to have four columns:

  • Label
  • Place
  • Start Date
  • End Date

Create a new function called prepareDataTable() to create and initialize the DataTable. We have to use the addColumn method to add each of the four columns. Once the columns have been added, use the addRow method to add all the four trips. Remember, dates have to be represented as Date objects and months are numbered 0-11 (instead of 1-12). Here’s how our function should look:

function prepareDataTable() {
  var dataTable = new google.visualization.DataTable();

  // Add columns
  dataTable.addColumn({ type: 'string', id: 'Label'});
  dataTable.addColumn({ type: 'string', id: 'Place'});
  dataTable.addColumn({ type: 'date', id: 'Arrival Date'});
  dataTable.addColumn({ type: 'date', id: 'Departure Date'});

  //Add Rows
  dataTable.addRow(['1', 'Berlin',
                    new Date(2014, 0, 15), new Date(2014, 1, 26)]);
  dataTable.addRow(['2', 'Paris', 
                    new Date(2014, 3, 20), new Date(2014, 6, 1)]);
  dataTable.addRow(['3', 'Madrid', 
                    new Date(2014, 6, 21), new Date(2014, 7, 30)]);
  dataTable.addRow(['4', 'Perth', 
                    new Date(2014, 10, 2), new Date(2014, 11, 5)]);

  return dataTable;
}

Take note that the first column of the DataTable is always treated as a label of a row by the Charts API.

Drawing the Timeline

Now that the data has been converted into a format that the Google Charts API understands, we can draw the timeline. To do this, we’ll create an instance of the Timeline class, and then pass the DataTable to its draw method. We’ll update the start method to do so:

function start() {
  // Pick the HTML element
  var timelineHolder = document.getElementById("timelineHolder");

  // Create an instance of Timeline
  var timeline = new google.visualization.Timeline(timelineHolder);
  var dataTable = prepareDataTable();

  // Draw the timeline
  timeline.draw(dataTable);
}

At this point, if you load your page using a browser, you will see a timeline that looks like this:

See the Pen b0522e3f0762ae90ce00c0f92438e8aa by SitePoint (@SitePoint) on CodePen.

Customizing the Timeline

Changing the appearance of the timeline involves creating a JSON object that contains one or more names of properties along with your preferred values for those properties.

For example, if we wish to change the background color of the timeline to #ffbb33 and use a single color for all the trips, say #669900, we will have to create the following JSON object:

var config = {
  backgroundColor: '#ffbb33',
  timeline: { singleColor: '#669900' }
}

We then pass this object as an additional parameter to the timeline’s draw method:

timeline.draw(dataTable, config);

On refreshing our page in the browser, our timeline will look like this:

See the Pen Google Charts Demo: Custom Colors by SitePoint (@SitePoint) on CodePen.

For a complete list of all available configuration options, refer to the Google Charts timeline documentation.

You may have noticed that the trips are placed one below the other, with each on its own line/row. This is because we used a different row label for each row. To place all trips on a single line, you will have to change the first column of your DataTable such that all the four entries have the same row label.

For our example, we’ll use Alice’s Travels as the label for all the rows. We’ll update our prepareDataTable function so that the addRow calls look like this:

dataTable.addRow(['Alice\'s Travels', 'Berlin', new Date(2014, 0, 15), 
                   new Date(2014, 1, 26)]);
dataTable.addRow(['Alice\'s Travels', 'Paris', new Date(2014, 3, 20), 
                   new Date(2014, 6, 1)]);
dataTable.addRow(['Alice\'s Travels', 'Madrid', new Date(2014, 6, 21), 
                   new Date(2014, 7, 30)]);
dataTable.addRow(['Alice\'s Travels', 'Perth', new Date(2014, 10, 2), 
                   new Date(2014, 11, 5)]);

The timeline will now look more compact:

See the Pen Google Charts Demo: Compact Timeline by SitePoint (@SitePoint) on CodePen.

Adding Interactivity

Our timeline is already interactive. Hovering over any trip displays a tooltip with some autogenerated content.

To add a custom behavior when a data item is clicked on, we have to add a handler for the select event using the google.visualization.events.addListener method. In the handler, we can use the getSelection method to determine which item was clicked.

Here’s a sample handler that displays the currently selected place. You can add it at the end of the start function, after calling the draw method:

google.visualization.events.addListener(timeline, 'select', function() {
  alert(dataTable.getValue(getSelection()[0].row, 1);
});

See the Pen Google Charts Demo: Showing an Alert Message by SitePoint (@SitePoint) on CodePen.

Conclusion

In this tutorial, I showed you how to use Google Charts to display events in a chronological order on a timeline chart that can easily be added to any web page. I also showed you how to customize the chart and make it interactive. To learn more about the timeline chart, refer to the Timeline Documentation.

Frequently Asked Questions (FAQs) about Adding a Timeline to Your Website with Google Charts

How can I customize the colors on my Google Chart timeline?

Google Charts provides a variety of customization options for your timeline, including color customization. You can use the ‘colors’ option to specify an array of colors for the timeline bars. Each color corresponds to a specific row in the data table. If you have more rows than colors, the chart will cycle through the color array again. For example, you can use the following code to set the colors:

var options = {
colors: ['#cbb69d', '#603913', '#c69c6e']
};

Can I add tooltips to my Google Chart timeline?

Yes, Google Charts allows you to add tooltips to your timeline. Tooltips are small pop-up boxes that appear when the user hovers over an item on the chart. They can provide additional information about the item, such as its value or label. You can customize the content and appearance of tooltips using the ‘tooltip’ option in the chart options. For example:

var options = {
tooltip: {isHtml: true}
};

How can I adjust the height and width of my Google Chart timeline?

You can adjust the height and width of your Google Chart timeline using the ‘height’ and ‘width’ options in the chart options. These options accept a number, which represents the height and width in pixels. For example:

var options = {
height: 400,
width: 600
};

Can I add a title to my Google Chart timeline?

Unfortunately, Google Charts does not support titles for timelines. However, you can create a title for your timeline using HTML and CSS. Simply create a heading element above your chart and style it as desired.

How can I add a legend to my Google Chart timeline?

Google Charts does not support legends for timelines. However, you can create a custom legend using HTML and CSS. Simply create a div element below your chart and add styled span elements for each item in your legend.

Can I use Google Charts to create a timeline with multiple rows?

Yes, Google Charts allows you to create timelines with multiple rows. Each row in your data table represents a separate bar in the timeline. You can use the ‘addRows’ method to add multiple rows to your data table. For example:

data.addRows([
['Washington', new Date(1789, 3, 30), new Date(1797, 2, 4)],
['Adams', new Date(1797, 2, 4), new Date(1801, 2, 4)],
['Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4)]
]);

How can I format the dates on my Google Chart timeline?

Google Charts provides a variety of options for formatting dates on your timeline. You can use the ‘hAxis.format’ option to specify a custom date format. For example, you can use the following code to format the dates as ‘yyyy’:

var options = {
hAxis: {
format: 'yyyy'
}
};

Can I use Google Charts to create a timeline with negative values?

No, Google Charts does not support timelines with negative values. Timelines are designed to represent events in time, so they only support positive values.

How can I add labels to the bars on my Google Chart timeline?

Google Charts does not support labels for timeline bars. However, you can use tooltips to provide additional information about each bar.

Can I use Google Charts to create a timeline with different bar heights?

No, Google Charts does not support different bar heights for timelines. All bars in a timeline have the same height. However, you can adjust the overall height of the timeline using the ‘height’ option.

Ashraff HathibelagalAshraff Hathibelagal
View Author

Hathibelagal is an independent developer and blogger who loves tinkering with new frameworks, SDKs, and devices. Read his blog here.

Chartsgoogle apiGoogle Tutorials & ArticlesLouisLtimeline
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week