Appcelerator Blog

The Leading Resource for All Things Mobile

Interactive Charts in Appcelerator Titanium

1 Flares 1 Flares ×
Interactive charts provide a powerful means to understanding data and data trends. As users interact with data on mobile devices more and more the need to be able to visualize data on mobile devices is increasing. Intraday/historical stock line charts, sales by region bar charts and pie chart distributions are just some examples of how data can be visualized in a chart. This blog post describes a simple method of adding high quality, cross device, interactive charts to your Titanium mobile applications by leveraging the Titanium web view control and the Highcharts JavaScript charting engine. Information about the Titanium web view control can be found here: http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.UI.WebView Information about Highcharts and Highstock can be found here: http://www.highcharts.com

Overview

The basic steps behind using a Titanium web view to display Highcharts JavaScript chart are as follows:
  1. Review the Highcharts web site to determine the type of chart you would like to use
  2. Create and assemble the Highcharts web assets (HTML and JavaScript files) and place in the titanium assets folder
  3. Add a web view to your titanium application and set the url to the local assets folder (e.g. html file)
  4. Set an onload event listener on the web view to insure that the web view is properly loaded and ready for you to send data to the JavaScript chart
  5. When the onload event is fired pass data to the web view and see your chart display

Review Highcharts Web Site

Before we start, head on over to Highcharts.com and read the documentation to understand its usage. You can use the demo link to see sample charts and also view in JSFiddle to tweak parameters to see how the charts operate and are configured and grab the code used when the chart suits your needs.
For my example, I was trying to create the following bar chart, which uses the default styling from the Highcharts site:

Create Assets for Titanium Project

  1. Download Highcharts from the web site
  2. Create an html folder under assets in your Titanium project and copy exporting.js, highcharts.js and jquery.js and an index.html file
For my example, the project folder structure and html asset files are shown below:
My index.html file is shown below:
<!DOCTYPE HTML>
<html>
	<head>
		<meta name="viewport" content="width=device-width">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Highstock Example</title>
		<script src="jquery.min.js"></script>
		<script src="highcharts.js"></script>
		<script src="exporting.js"></script>
		<script type="text/javascript">
			function plotChart(cat, mtd, ytd) {
		        Ti.API.info('Webview: plotChart()');

		        new Highcharts.Chart({
					chart: {
						renderTo: 'container',
						backgroundColor: null,
						plotBackgroundColor: null,
		                type: 'column'
		            },
		            credits:{
						enabled:false
					},
					title:{
						text:null
					},
					exporting : {
						enabled : false
					},
		            xAxis: {
		                categories: cat
		            },
		            yAxis: {
		                min: 0,
		                title: {
		                    //text: '$M'
		                    text: ''
		                }
		            },
		            plotOptions: {
		                column: {
		                    pointPadding: 0.2,
		                    borderWidth: 0
		                }
		            },
		            series: [{
		            	name: 'MDT',
		                data: mtd
		            },{
		            	name: 'YTD',
		                data: ytd
		            }]
				});
			}
		</script>
	</head>

	<body>
		<div id="container" style="height: 300px; width: 100%"></div>
	</body>
</html>
From the index.html file above, you can see that the Highcharts chart creation code is contained inside a JavaScript function plotChart(). The function accepts the category (cat), month-to-date (mtd) and year-to-date (ytd) data that will be passed in from the titanium application.

Add a Web View and set the URL

The following Alloy view code sample adds a web view to the screen and sets the url to the index.html.
<WebView id='chartWebView' url='/html/index.html'></WebView>

Set an onload Event Listener and Load Data

The following Alloy controller code sample sets an onload event listener and makes a request for data from a Node.ACS service. When the data is retrieved, the data is passed to the web view Highcharts JavaScript by calling the plotChart() method described above using the evalJS web view method.
$.chartWebView.addEventListener('load', function() {
	Ti.API.info('chartWebView ready');

	nodesqldashboard.services_getData({}, function(r,e){
    		Ti.API.info("e = "+JSON.stringify(e));
    		if(!e.success){
    			Ti.API.info("Error: "+e.error);
    			return;
    		}

    		$.chartWebView.evalJS('plotChart('+JSON.stringify(_.pluck(r.data, 'region'))+','+JSON.stringify(_.pluck(r.data, 'mtd'))+','+JSON.stringify(_.pluck(r.data, 'ytd'))+')');
    });
});
When the chart is loaded, it will animate on the screen and the user will be able to interact with the chart elements.

Examples

An example of a historical stock price line chart on iPhone (left) and Android (right) is show below:
An example of a Sales by Region bar chart on iPhone (left) and Android (right) is show below:
In this post we saw how Highcharts can be used in conjunction with the Titanium web view to create cross device interactive charts. We saw how easy it is to use the Titanium web view control to load and interact with the Highcharts JavaScript without the need to alter the standard development workflow. All the code is written in Titanium Classic syntax. However, Ricardo Alcocer wrote a proof-of-concept of how this can be converted into an Alloy Widget.

1 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 1 Email -- 1 Flares ×

4 Comments

  1. Yanko Valera

    I am having issues with evalJS in Android 2.3 emulators.
    (dalvikvm: JNI WARNING: jarray 0x4074be98 points to non-array object (Ljava/lang/String;))

    It’s there any solution?

    Regards

  2. Will the same work for Fusioncharts?

  3. Eric Valverde

    Hi,
    Is anyone having problems to view the charts on KitKat? It used to work fine but it’s not working on android phones using KitKat…

    Eric

Comments are closed.

Sign up for updates!

Become a mobile leader. Take the first step to scale mobile innovation throughout your enterprise.
Get in touch
computer and tablet showing Appcelerator software
Start free, grow from there.
1 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 1 Email -- 1 Flares ×