Twitter: raymondcamden


Address: Lafayette, LA, USA

Quickie AIR for Mobile Geolocation Example

11-05-2010 8,148 views Mobile, Flex Comments

Last night I read over Rich Tretola's excellent Geolocation for AIR/Mobile example. He demonstrates how to a) check and see if Geolocation is available (it may not be) and how to handle the response from the GPS system on the device. I thought it might be interesting to tie that to a change I made to the Adobe Groups remote API last night. I added a method that would return user groups based sorted by distance based on a longitude and latitude. For my testing I had done typed in values (everyone knows their longitude and latitude, right?) but I figured it would be even easier with AIR.

Let's take a look at the application I built. All in all it is pretty unrealistic since it has a grand total of one page, but I wanted something I could write in a few minutes.

view plain print about
1<?xml version="1.0" encoding="utf-8"?>
2<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
3        xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx"
4        title="UG Locator" viewActivate="init()">

5
6    <fx:Declarations>
7        <mx:HTTPService id="groupsHTTPService" url="http://groups.adobe.com/api/group.cfc" method="get" result="handleResult(event)" fault="handleFault(event)" />
8    </fx:Declarations>
9    
10    <fx:Script>
11        <![CDATA[
12            import com.adobe.serialization.json.*;
13            
14            import flash.events.GeolocationEvent;
15            import flash.sensors.Geolocation;
16            
17            import mx.collections.ArrayCollection;
18            import mx.collections.ArrayList;
19            import mx.rpc.events.FaultEvent;
20            import mx.rpc.events.ResultEvent;
21            
22            private var geoLocation:Geolocation;
23            
24            [Bindable] private var groups:ArrayCollection;
25            
26            private function init():void {
27                groups = new ArrayCollection();
28                
29                locate();    
30                /* used for testing... */
31                /*
32                var evt:GeolocationEvent = new GeolocationEvent(GeolocationEvent.UPDATE,false,false,30.2009,-92.0572);
33                handleLocationRequest(evt);
34                */

35            }
36            
37            public function handleFault(evt:FaultEvent):void {
38                //bug.text = evt.toString();
39                geoLocation.removeEventListener(GeolocationEvent.UPDATE, handleLocationRequest);
40            }
41            
42            public function handleResult(evt:ResultEvent):void {
43                var data:Object = JSON.decode(evt.result as String);
44                groups.source = data as Array;
45                geoStatus.text = "There were "+data.length + " groups within 200 miles of your location.";
46            }
47            
48            private function locate():void {
49                if(Geolocation.isSupported==true){
50                    geoLocation = new Geolocation();
51                    geoLocation.addEventListener(GeolocationEvent.UPDATE, handleLocationRequest);
52                } else {
53                    geoStatus.text = "Geolocation feature not supported";
54                }
55            }
56            
57            private function handleLocationRequest(event:GeolocationEvent):void {
58                geoLocation.removeEventListener(GeolocationEvent.UPDATE, handleLocationRequest);
59                geoStatus.text="Finding groups near your location... ";
60                var lat:Number = event.latitude;
61                var lon:Number = event.longitude;
62                var req:Object = new Object();
63                req.method="getgroupswithindistance";
64                req.longitude = lon;
65                req.latitude = lat;
66                req.range = 200;
67                groupsHTTPService.request = req;
68                groupsHTTPService.send();
69            }
70            
71        ]]>

72    </fx:Script>
73    
74    <s:VGroup width="100%" height="100%" paddingLeft="5" paddingRight="5" paddingTop="5">        
75        
76        <s:Label id="geoStatus" width="100%"/>
77        
78        <s:List id="groupList" dataProvider="{groups}" width="100%" height="100%">
79            <s:itemRenderer>
80                <fx:Component>
81                    <s:MobileIconItemRenderer labelFunction="displayGroup" messageFunction="displayMessage" iconField="AVATAR">
82                        <fx:Declarations>
83                            <mx:NumberFormatter id="myNumFormat" precision="0" />                    
84                        </fx:Declarations>
85                        <fx:Script>
86                            <![CDATA[
87                                private function displayGroup(ob:Object):String {
88                                    return ob.NAME;
89                                }
90                                private function displayMessage(ob:Object):String {
91                                    return myNumFormat.format(ob.DISTANCE) + " miles away.";
92                                }
93                                
94                            ]]>

95                        </fx:Script>
96                    </s:MobileIconItemRenderer>
97                </fx:Component>
98            </s:itemRenderer>
99            
100        </s:List>
101    </s:VGroup>
102    
103</s:View>

The application begins by running a call to my locate method. The code here is a complete copy of Rich's code but essentially it just does the hardware check. As soon as you create a Geolocation object you can then begin listening for the result. I do that in handleLocationRequest. Once I've got your location I stop listening. (I assume you are standing still, motionless, like I am most of the day unfortunately.) Once I've got that I then just fire off a HTTP request to the API. Unfortunately my API for Groups is JSON only (for now), but it's easy enough to work with JSON if you use as3corelib. Once I push my data to my list - it gets rendered. I'm still learning Flex 4 but I love how I was able to have a mini "component" right within the page itself. Very convenient! And the result?

I've added APK as a mime type to IIS so hopefully the download link will work. I'd include the full source but outside of the XML that's it. Don't forget that in AIR for Mobile apps you have to be cognizant of the additional permissions your application may require. Within my android manifest block I added:

view plain print about
1<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Enjoy! Oh - two quick notes.

While pushing out my code to the phone I noticed, for the first time, that it seemed to 'latch' on to the application. I had to manually delete the application one time. I didn't see that again so maybe it was just a fluke. But keep that in mind if you don't see your application refreshing when running on the hardware.

Lastly - I still need to share the source code for the Death Clock application I blogged about before MAX. Will do so soon.

Download attached file

0 Comments

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty