Saturday, April 7, 2012

GWT dygraph example using visualization datatable

Here is a quick example of how to create a dygraph using GWT and visualization api to get the datatable.

1. Add dygraph-gwt.jar to your build path and these inherits tags in your mysamplegwtproj.gwt.xml file

<inherits name="com.google.gwt.visualization.Visualization"/>
<inherits name="org.danvk.dygraphs"/>

2. Add the following script tag in mysamplegwtproject.html file

<script type="text/javascript" src="dygraph-combined.js">
<script type="text/javascript" src="http://www.google.com/jsapi">
3. Add the following code in your onModuleLoad() function-



        final VerticalPanel vp = new VerticalPanel();
        vp.setWidth("700px");
        vp.setHeight("700px");
        VisualizationUtils.loadVisualizationApi(new Runnable() {
            @Override
            public void run() {
                Query q = Query
                        .create("mysampleproj/getMyDatatable?params=2&id=1");

                q.send(new Callback() {
                    @Override
                    public void onResponse(QueryResponse response) {
                        JavaScriptObject jdygraph = createDygraph(
                                vp.getElement(), response.getDataTable(), 0,
                                100);
                    }
                });
            }
        }, LineChart.PACKAGE);

        RootPanel.get().add(vp);

4. Here is the JSNI function which actually creates the dygraph.


public static native JavaScriptObject createDygraph(Element element,
            DataTable dataTable, double minY, double maxY) /*-{
        var chart = new $wnd.Dygraph.GVizChart(element);
        chart.draw(dataTable, {
            valueRange : [ minY, maxY ],
            displayAnnotations : true,
            showRangeSelector : true,
            legend : 'always',
            labelsDivStyles : {
                'textAlign' : 'right'
            },
            title : 'TITLE',
            titleHeight : 25,            
            axes : {
                x : {
                    pixelsPerLabel : 50
                }
            }            
        });
        return chart;
    }-*/;

Hope this helps. Suggestions/improvements are welcome.

===============================================================
 

3 comments:

Anonymous said...

Thanks Harpreet, but could you please let us know how you specified your DataTable? I am getting the following exception:

com.google.gwt.core.client.JavaScriptException: (TypeError): $wnd.Dygraph is undefined

and maybe this is due to different definition of my and your DataTables. Does your createDygraph method creates a graph for any DataTable one passes in, or?

Thanks, Darko

Harpreet said...

Can you check if dygraph-combined.js was loaded onto the page? from what it looks like it is a problem with not being able to find dygraph on the page.

Anonymous said...

Where is dygraph-gwt.jar? I cannot find it following your link. Thanks!