Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Creating Charts and Graphs - Adobe Flex 2

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Client Technologies - Adobe Flex 2 and Rich Internet Applications

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Creating Charts and Graphs - Adobe Flex 2

To use Flex’s charting components, you must first install Flex Charting.

Creating Charts and Graphs

To use Flex’s charting components, you must first install Flex Charting. A trial version is available at  www.adobe.com/go/tryflex. Installation instructions are available at  www.ado- be.com/support/documentation/en/flex/2/install.html#installingcharts.

To demonstrate Flex’s charting capabilities, we’ve added a Chart View section to our weather application (Fig. 18.22) and populated it with two charts. The first is a Line-Chart that separately plots the high and low temperatures against the date. The user can mouse over any point of data and a data tip will tell the user whether it is a high or low temperature, the date and the temperature. The second chart is a CandlestickChart, dis-playing the range of temperatures for each day. This element also uses data tips to show greater detail. You can test a live version of this application at test.deitel.com/exam-

ples/iw3htp4/flex/weatherChart/.

 

A chart is just another type of user interface element. In addition to the chart types mentioned in Section 18.2, a full list of charting components is available from Adobe at

livedocs.adobe.com/flex/201/html/charts_intro_108_03.html.

 

Figure 18.23 is a listing of the weather application with charting capabilities added. The first change we make in the code is to create an ArrayCollection to make our weather data available to a chart. To do this, we add the code [Bindable] public var weatherArray : ArrayCollection; in lines 31–32. We want it to be Bindable so that whenever the ArrayCollection is changed, the chart updates automatically. Next, we add lines 47 and 70 to create text showing the place name in the Chart View that acts just like the text in our Forecast View. We also add line 182 to animate changes in a chart’s data.


1     <?xml version = "1.0" encoding = "utf-8" ?>

 

2     <!-- Fig. 18.23: weatherChart.mxml -->

 

3     <!-- Charting weather data in Flex 2 -->

 

4     <mx:Application xmlns:mx = "http://www.adobe.com/2006/mxml"

 

5           layout = "absolute"

 

6           xmlns = "*" xmlns:yahoo = "com.yahoo.webapis.maps.*"

 

7           creationComplete = "initMap();" >

8

9        <mx:Script source = "map.as" />

 

10

11          <mx:Script>

 

12          <![CDATA[

 

13                 import mx.controls.dataGridClasses.DataGridColumn;

 

14                 import mx.rpc.events.ResultEvent;

 

15                 import mx.managers.CursorManager;

 

16                 import mx.controls.Alert;

 

17                 import mx.collections.ArrayCollection;

 

18                 import flash.events.MouseEvent;

19

20                 // define default namespace so we don't have to write it every time

 

21                 default xml namespace = "http://www.webservicex.net";

22

23                 [Bindable]

 

24                 private var xmlData : XML;

 

25                 [Bindable]

 

26                 private var highLowTemp : String;

 

27                 [Bindable]

 

28                 private var fiveDayForecast : String = "";

 

29                 [Bindable]

 

30                 public var weatherArray : ArrayCollection;

 

31                 [Bindable]

 

32                 private var placeName : String;

33

34                 // handle getWeatherButton click action

 

35                 private function getWeather() : void

36                 {

 

37                       // disable button while request is pending

 

38                       getWeatherButton.enabled = false;

39

40                       // hide the old forecast data before displaying new data

 

41                       forecastBox.visible = false;

42

43                       // reset place name while loading new data

 

44                       placeNameText.text = "";

45

46                       // reset place name while loading new data

 

47                       placeNameChartText.text = "";

48

49                       // show the loading progress bar

 

loadingBar.visible = true;

52                       // request the new data

 

53                       weatherService.GetWeatherByZipCode.send();

 

54                 } // end function getWeather

55

56                 private function weatherResultHandler(event : ResultEvent) : void

57                 {

 

58                       // save the result of the web service as XML

 

59                       xmlData = XML( event.result );

60

61                       // check that result is valid by checking length of StateCode

 

62                       if ( xmlData.GetWeatherByZipCodeResult[ 0 ].

63                              StateCode.text().length() != 0 )

{

 

65        // set placeNameText to the city and state of the zip code

66        placeName = xmlData.GetWeatherByZipCodeResult[ 0 ].

67                    PlaceName.text() + ", " +

68                    xmlData.GetWeatherByZipCodeResult[ 0 ].StateCode.text();

69        placeNameText.text = "5 Day Forecast for " + placeName;

70                    placeNameChartText.text = "5  Day  Forecast  for  " + placeName;   

71                               

72        // set image, temperature and date for each day

73        setData( weatherImage0, weatherTemp0, weatherDay0, 0 );

74        setData( weatherImage1, weatherTemp1, weatherDay1, 1 );

75        setData( weatherImage2, weatherTemp2, weatherDay2, 2 );

76        setData( weatherImage3, weatherTemp3, weatherDay3, 3 );

77        setData( weatherImage4, weatherTemp4, weatherDay4, 4 );

78                               

79        forecastBox.visible = true;

80                               

81        // save today’s high/low as a string

82        highLowTemp =  xmlData.GetWeatherByZipCodeResult.

83                    Details.WeatherData.MaxTemperatureF[ 0 ].text() +

84                    "/" + xmlData.GetWeatherByZipCodeResult.Details.

85                    WeatherData.MinTemperatureF[ 0 ].text();

86                               

87        // save the five-day forecast as a string

88        fiveDayForecast = highLowTemp;

89                               

90        for ( var i : int = 1; i < 5; i++ )

91        {          

92                    fiveDayForecast += ", " + xmlData.

93                    GetWeatherByZipCodeResult.Details.WeatherData.

94                    MaxTemperatureF[ i ].text() + "/" + xmlData.

95                    GetWeatherByZipCodeResult.Details.

96                    WeatherData.MinTemperatureF[ i ].text();

97        } // end for

98                               

99        // place a marker on the map with the forecast

100     mapController.addCustomPOIMarker(

101                 zipcode.text, placeName, highLowTemp, fiveDayForecast,

102                 0x990099, 0xFFFFFF);

103                            

                                   

104     mapController.setCenterByAddressAndZoom(

105     zipcode.text, 7, 0 );

106    

107     // begin charting functionality

108    

109     // saves date, high and low temp into an ArrayCollection

 

110     // so it can act as a chart's dataProvider

 

111     weatherArray = new ArrayCollection( );

112

 

            for (     var j : int = 0; j < weatherService.GetWeatherByZipCode.                   

113                                                    

114                 lastResult.GetWeatherByZipCodeResult.Details.                    

115                 WeatherData.length(); j++ )                       

116     {                                                                      

117     //          create the object to be added to the array           

118                             var weatherDataObject : Object = new Object();                        

119                                                                                        

120     //          extract the data from the e4x-formatted result    

121                             weatherDataObject.Date =  weatherService.                 

122                                         GetWeatherByZipCode.lastResult.                     

123                                         GetWeatherByZipCodeResult.Details.WeatherData[ j ].Day;             

124                             weatherDataObject.HighTemp = weatherService.                    

125                                         GetWeatherByZipCode.lastResult.                     

126                                         GetWeatherByZipCodeResult.Details.               

127                                         WeatherData[ j ].MaxTemperatureF;                    

128                             weatherDataObject.LowTemp = weatherService.                     

129                                         GetWeatherByZipCode.lastResult.                     

130                                         GetWeatherByZipCodeResult.Details.               

131                                         WeatherData[ j ].MinTemperatureF;                     

132                                                                                        

133     //          add the object to the array 

134                             weatherArray.addItem( weatherDataObject );    

135                           } //end for

 

136                     // end charting functionality

137                     }

138                     else

139                     {

 

140                           Alert.show( "Invalid zip code" );

141                     }

 

142                     // hide the loading progress bar

 

143                     loadingBar.visible = false;

144

145                     // enable getWeatherButton

 

146                     getWeatherButton.enabled = true;

 

147               } // end function weatherResultHandler

148        

149               private function setData( forecastImage : Image,

 

150                     tempText : Text, dateText : Text, i : int ) : void

151               {

 

152                     // set the image for each day

 

153                     forecastImage.source = xmlData.GetWeatherByZipCodeResult.

 

Details.WeatherData.WeatherImage[ i ].text();

156                     // set the temperature for each day

 

157                     tempText.text = xmlData.GetWeatherByZipCodeResult.

 

158                           Details.WeatherData.MaxTemperatureF[ i ].text() +

 

159                           "\n" + xmlData.GetWeatherByZipCodeResult.Details.

 

160                           WeatherData.MinTemperatureF[ i ].text();

161

162                     // set the date for each day

 

163                     dateText.text = xmlData.GetWeatherByZipCodeResult.

 

164                           Details.WeatherData.Day[ i ].text();

165               }

166        ]]>

 

167        </mx:Script>

168

169        <!-- show/hide animations for forecast boxes -->

 

170        <mx:Parallel id = "forecastAnimationIn">

 

171               <mx:Fade duration = "1000" alphaFrom = "0.0" alphaTo = "1.0" />

 

172               <mx:Zoom zoomWidthTo = "1" zoomHeightTo = "1" zoomWidthFrom = "0"

 

173                     zoomHeightFrom = "0" />

 

174        </mx:Parallel>

175

176        <mx:Parallel id = "forecastAnimationOut">

 

177               <mx:Fade duration = "500" alphaFrom = "1.0" alphaTo = "0.0" />

 

178               <mx:Zoom zoomWidthTo = "0" zoomHeightTo = "0" zoomWidthFrom = "1"

 

179                     zoomHeightFrom = "1" />

 

180        </mx:Parallel>

181

182     <mx:SeriesInterpolate  id = "interpolateEffect"  duration = "1000" />

 

183

184        <!-- WebService description -->

 

185        <mx:WebService id = "weatherService"

 

186               wsdl = "http://www.webservicex.net/WeatherForecast.asmx?WSDL"

 

187               fault = "Alert.show( event.fault.faultString )"

 

188               result = "weatherResultHandler( event )"

 

189               showBusyCursor = "true">

 

190               <mx:operation name = "GetWeatherByZipCode" resultFormat = "e4x">

 

191                     <mx:request>

 

192                           <ZipCode>{ zipcode.text }</ZipCode>

 

193                     </mx:request>

 

194               </mx:operation>

 

195        </mx:WebService>

196

197        <!-- user interface begins here -->

 

198        <mx:Panel title = "Weather" width = "100%" height = "100%">

 

199               <mx:Accordion id = "accordion" width = "100%" height = "100%"

 

200                     creationPolicy = "all">

 

201                     <mx:VBox label = "Forecast View" width = "100%" height = "100%">

 

<mx:ApplicationControlBar

203     defaultButton =        "{ getWeatherButton }">     

204     <mx:Label width       = "100%"       

205     text = "Enter a zip code:" />           

206     <mx:TextInput id = "zipcode" left = "10"   />

207     <mx:Button id =        "getWeatherButton" label   = "Get Weather"

208     click = "getWeather()" left = "10" />          

209     </mx:ApplicationControlBar>

210    

211     <mx:Text fontWeight = "bold" id = "placeNameText" />

212     <mx:ProgressBar id = "loadingBar" indeterminate = "true"

213     labelPlacement = "bottom" visible = "false" minimum = "0"

214     maximum = "100" label = "Loading Weather Data"

215     direction = "right" width = "75%" />

216    

217     <!-- forecastBox holds the five-day forecast -->

218     <!-- start off as hidden, define show and hide effects -->

219     <mx:HBox id = "forecastBox" width = "100%" height = "100%"

220     visible = "false" showEffect = "{ forecastAnimationIn }"

221     hideEffect = "{ forecastAnimationOut }">

222     <mx:VBox id = "forecastBox0" horizontalAlign = "center"

223     borderStyle = "solid" width = "20%" height = "0%">

224     <mx:Text id = "weatherDay0" />

225     <mx:Image id = "weatherImage0" />

226     <mx:Text id = "weatherTemp0" />

227     </mx:VBox>

228    

229     <mx:VBox horizontalAlign = "center"

230     borderStyle = "solid" width = "20%">

231     <mx:Text id = "weatherDay1" />

232     <mx:Image id = "weatherImage1" />

233     <mx:Text id = "weatherTemp1" />

234     </mx:VBox>

235    

236     <mx:VBox horizontalAlign = "center"

237     borderStyle = "solid" width = "20%">

238     <mx:Text id = "weatherDay2" />

239     <mx:Image id = "weatherImage2" />

240     <mx:Text id = "weatherTemp2" />

241     </mx:VBox>

242    

243     <mx:VBox horizontalAlign = "center"

244     borderStyle = "solid" width = "20%">

245     <mx:Text id = "weatherDay3" />

246     <mx:Image id = "weatherImage3" />

247     <mx:Text id = "weatherTemp3" />

248     </mx:VBox>

249    

250     <mx:VBox horizontalAlign = "center"

251     borderStyle = "solid" width = "20%">

252     <mx:Text id = "weatherDay4" />

253     <mx:Image id = "weatherImage4" />

254     <mx:Text id = "weatherTemp4" />

255     </mx:VBox>

256     </mx:HBox>

257     </mx:VBox>

258     <mx:VBox label = "Map View" width = "100%" height = "100%">

259     <!-- create Yahoo! Map -->

260     <yahoo:YahooMapService id = "yahooMap" UUID = "{ UUID }"

261     swfDomId = "{ swfDomID }"

262     apiId = "{        YahooAPIKey }"      

263     mapURL = "{ mapURL }" width = "600" height = "400" />        

264     <mx:HBox>              

265     <mx:Button    label = "Back"          

266     click = "accordion.selectedIndex=0;" />   

267     <mx:Button    label = "Clear"         

268     click = "mapController.removeAllMarkers();" />  

269     </mx:HBox>

 

270     </mx:VBox> <!-- end "Map View" Section -->

271    

272     <!-- begin "Chart View" pane -->

 

273     <mx:VBox label = "Chart View" width = "100%" height = "100%">

 

274     <mx:Text fontWeight = "bold" id = "placeNameChartText" />

 

275     <mx:LineChart id = "lineChart" width = "100%" height = "100%"

 

dataProvider = "{      weatherArray }" showDataTips = "true">            

276                                        

277     <mx:verticalAxis>                            

278     <mx:LinearAxis baseAtZero = "false" />             

279     </mx:verticalAxis>                           

280     <mx:horizontalAxis>                       

281     <mx:CategoryAxis categoryField = "Date"                      

282     title = "Date" />                     

283     </mx:horizontalAxis>                      

284     <mx:series>                          

285     <mx:LineSeries        yField = "HighTemp"                      

286     displayName = "High Temp"                     

287     showDataEffect = "{ interpolateEffect }" />                     

288     <mx:LineSeries        yField = "LowTemp"                       

289     displayName = "Low Temp"                      

290     showDataEffect = "{ interpolateEffect }" />                     

291     </mx:series>                         

292     </mx:LineChart>

 

293     <mx:CandlestickChart id = "candlestickChart" width = "100%"

            height = "100%" showDataTips = "true"             

294                            

295     dataProvider = "{ weatherArray }">                      

296     <mx:verticalAxis>                

297     <mx:LinearAxis baseAtZero = "false" />             

298     </mx:verticalAxis>               

299     <mx:horizontalAxis>                       

300     <mx:CategoryAxis categoryField = "Date"                      

301     title = "Date"/>                      

302     </mx:horizontalAxis>                      

303     <mx:series>              

304     <mx:CandlestickSeries openField = "HighTemp"                     

305     highField = "HighTemp" lowField = "LowTemp"                       

306     closeField = "LowTemp"                

307     showDataEffect = "{ interpolateEffect }" />                     

308     </mx:series> 

309     </mx:CandlestickChart>

 

310     </mx:VBox> <!-- end "Chart View" section -->

 

311     </mx:Accordion>

 

312     </mx:Panel>

 

313     </mx:Application>

 

Fig. 18.23 | Charting weather data in Flex 2.

 

Lines 113–135 declare a for statement that iterates over the WeatherData objects returned by the weatherService WebService. Inside the for statement, we create a weatherDataObject and give it the attributes Date, HighTemp, and LowTemp (lines 121–131). We give these attributes values from the XML returned by the web service. Finally, we add each weatherDataObject to weatherArray (line 134).

 

We also add a new pane in the Accordion for our chart, a VBox called Chart View (lines 273–310). This contains a Text element called placeNameChartText (line 274). This ele-ment serves an identical purpose to placeNameText (line 211). Next, we add a LineChart element (lines 275–292). This LineChart has the dataProvider attribute set to { weath- erArray } to indicate that the data presented in the chart is bound to weatherArray. We also specify that showDataTips is true (line 276), meaning that when the user mouses over a data point on the graph, a data tip will pop up, giving the user more detailed information about that point. Line 278 specifies that the baseAtZero attribute of the verticalAxisLinearAxis is false. This way, the graph displays the range of temperatures only from lowest to highest, rather than starting at zero. Inside the horizontalAxis element (lines 280–283), we specify one CategoryAxis named Date. The CategoryAxiscategory-Field attribute is set to "Date", meaning that the axis receives data from the Date field of weatherArray. Next, we specify LineSeries elements, located in the series element (lines 284–291). The first LineSeriesyField attribute is set to "HighTemp", which means that the LineSeries gets its data from the HighTemp field of weatherArray. We also set showDataEffect to "{ interpolateEffect }". This calls the interpolateEffect SeriesEffect that we created every time the data is updated. We also create a second LineSeries displaying LowTemp from weatherArray, using the same effect.

 

The second chart is a CandlestickChart (lines 293–309). This chart also sets show-DataTips to "true" and uses the same dataProvider (weatherArray). It also sets the ver-ticalAxis baseAtZero attribute to "false" and has a horizontalAxis that displays the Date. In the CandlestickChart’s series element (lines 303–307) is a Candlestick-Series with several attributes. The four attributes that define the data it displays are open-Field, highField, lowField and closeField. A CandlestickChart is designed to display financial data, such as stock prices. Therefore, it requires a start value and end value in addition to a high and low value. Since we have only high and low data for the weather, we place HighTemp in both openField and highField. Similarly, we place LowTemp in both closeField and lowField. We use interpolateEffect as the showDataEffect. Finally, the swfDomID constant in map.as must point to the filename of our application without .swf (in this case, weatherChart).

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.