Alicia
Alicia

Reputation: 174

How to use Google Visualization chart with GWT and AjaxLoader

I'm trying to incorporate interactive charts into a GWT app using Google Visualization. I don't want to connect to the Google App engine. I'd also like to use the GWT APIs instead of embedding javaScript in my code. I'm trying to follow the examples SimpleViz and HelloAjaxLoader in gwt-google-apis, but the chart does not load. I've added the ajaxloader and visualization jars to my classpath and inherits in gwt.xml. In the following code, the alert "in onModuleLoad" displays, but not "in run".

My code:

public class SimpleViz implements EntryPoint {  
   private VerticalPanel container;
   private ImagePieChart chart;

public void onModuleLoad() {
   Window.alert("In onModuleLoad");
   container = new VerticalPanel();
   RootPanel.get().add(container);    
   container.getElement().getStyle().setPropertyPx("margin", 10);
   container.setSpacing(10);
   container.add(new Label("Pie Chart Example"));

   AjaxLoader.init();     
   AjaxLoader.loadApi("visualization", "1", new Runnable() {   

      public void run() {
          Window.alert("In run");
          chart=new ImagePieChart();
          container.add(chart);
           draw();
      }
    }, null);

 }


private void draw() {
    // Prepare the data
    DataTable dataTable = DataTable.create();
    dataTable.addColumn(ColumnType.STRING, "Task");
    dataTable.addColumn(ColumnType.NUMBER, "Hours per Day");
    dataTable.addRows(5);
    dataTable.setValue(0, 0, "Work");
    dataTable.setValue(0, 1, 11);
    dataTable.setValue(1, 0, "Sleep");
    dataTable.setValue(1, 1, 7);
    dataTable.setValue(2, 0, "Watch TV");
    dataTable.setValue(2, 1, 3);
    dataTable.setValue(3, 0, "Eat");
    dataTable.setValue(3, 1, 2);
    dataTable.setValue(4, 0, "Commute");
    dataTable.setValue(4, 1, 1);

    // Set options
    ImagePieChart.Options options = ImagePieChart.Options.create();
    options.setBackgroundColor("#f0f0f0");
    options.setIs3D(false);
    options.setTitle("So, how was your day?");

    // Draw the chart
    chart.draw(dataTable, options);
  }

}

As a follow-up question, are these libraries current and well maintained or should I look for a different solution?

Upvotes: 1

Views: 633

Answers (1)

Andrei Volgin
Andrei Volgin

Reputation: 41089

This is how I do it (and it works).

In your module gwt.xml file add the following line:

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

This line inherits gwt-visualization.jar.

Then in your code:

Runnable onLoadCallback = new Runnable() {
    @Override
    public void run() {
        draw();
    }
};
VisualizationUtils.loadVisualizationApi(onLoadCallback, CoreChart.PACKAGE);

You don't need AjaxLoader.

Upvotes: 1

Related Questions