Using Appcelerator Titanium and Figma to simulate a Derby App

profiletestnik2
291-305.pdf

Getting the Tools You Need ❘ 291

Development

From this point on the chapter discusses the application layout and gives an explanation of Titanium as a whole.

Project Structure

The layout of the project is displayed in the Application Explorer tab as shown in Figure 10-9. The options are:

➤ Resources: All project elements go in this folder. Each separate app pane can be held in a single JavaScript fi le, to include later. I recommend creating a separate folder for images, styles, and database scripts under this folder.

➤ android: This is the folder to use when building specifi cally for Android. It holds your Android-specifi c UI elements.

➤ iPhone: This is the folder to use specifi cally when building for iPhone. It holds all of your iPhone-specifi c UI elements.

➤ app.js: This runs when the application is started. It contains all your references to other classes, views, UI elements, and databases, and is where all of your global variables are declared. This is where you include your windows from the resources folder.

Covered next are the basics of Titanium and how you will use it to develop your mobile applications.

Titanium Basics

When you mention JavaScript to most web developers, they cringe. Most times, in fact, it’s not JavaScript they hate, it’s the document object model (DOM) of most web browsers that causes cross- browser inconsistencies. When it comes down to it, JavaScript is a beautiful language with many advanced programming concepts, taking many concepts from the functional world but staying true to its roots as an OO language. JavaScript was initially created to add interactivity to web pages. Titanium handles UI events and builds the UI as well. JavaScript is a loosely typed language, so all variables and function references are declared with the var keyword.

Variables, classes, and functions are global unless properly namespaced: be sure to remember this when you are naming elements in your application.

Namespaces are how you prevent naming collisions due to the global nature of JavaScript. A namespace is a wrapper that persists your scope.

The following code shows two examples of creating a namespace around a variable and creating a function. The fi rst is the simplest form, directly and specifi cally creating each part of the object. The second is a more elegant form, initializing the namespace with the intended fi eld and function.

var testNS = {}; testNS.name = “Namespace Test”; testNS.hello = new function(){ return ‘Hello from ‘ + testNS.name; };

c10.indd 291c10.indd 291 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

292 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

or

var testNS = { name: “Namespace Test”; hello: function(){ return ‘Hello from ‘ + testNS.name; } };

Getting into Titanium specifi cally with JavaScript, you can create a button element to the window with “Click Me” as the title of the button. The next step is to add an event listener to catch the click event. Finally, add the button to the main window and show that window. This is standard practice in Titanium. I recommend that you create a separate fi le for each window you want to have in your application, and a fi le that is included to hold all of your UI element declarations. By doing that you can leave the window class itself to event handler functions and other per-page processing functions.

Titanium.UI.setBackgroundColor(‘#000’); var mainWindow = Ti.UI.createWindow({ title:’Roster’, backgroundColor:’#fff’ });

var btnHello = Titanium.UI.createButton({ title: ‘Click Me’ })

btnHello.addEventListener(‘click’,function(e) { Titanium.API.info(“Button was clicked”); alert(‘Hello World!’); });

mainWindow.add(btnHello); mainWindow.show();

Creating User interfaces

Titanium.include() is the main way to include views in your application. Effectively no different than a script tag in an HTML page, Titanium.include() allows for separation of concerns with the resource allocation to happen in one place. Examples of this are shown later in the chapter.

Basic UI Elements in Titanium

All of the elements mentioned in this section are the specifi cally called out in the Titanium API documentation. I have gone over each individually so that you can feel comfortable with them before starting development.

➤ ActivityIndicator: This element is the platform-specifi c activity throbber represented in the status bar of your device.

➤ Button: This is the standard button element.

c10.indd 292c10.indd 292 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Getting the Tools You Need ❘ 293

➤ DashboardItem: This is a very specifi c element that is rendered in the UI view type DashboardView. It is effectively an image that can be moved around the UI when in a DashboardView, and can have a badge overlay (like the mail icon in iOS).

➤ ImageView: This is the standard image element.

➤ Label: This is the standard UI element for labels. (Noneditable text displayed in your view.)

➤ ProgressBar: Everyone’s favorite element to hate, this is a highly customizable UI element to show relative completion metrics.

➤ SearchBar: This is the OS-specifi c search bar exposed in Titanium. It melds the search button and text fi eld together in a single UI element. It has all of the main event handlers for managing click, change, and blur events.

➤ Slider: This provides granular selection for the user when working with things like volume, opacity, or anything that requires a fi ne level of control.

➤ Switch: Represented by the on/off slider, and a checkbox on/off on iOS and Android respectively, this is the UI element to represent boolean states.

➤ TextArea, TextField: These are the standard editable text objects. Use TextArea for multi- line and TextField for single line.

Basic UI View Elements in Titanium

The following elements are types of views and containers to be used inside your Titanium app.

➤ AlertDialog: This is the modal window that is created by an alert(‘message’) call. You can also reference it by using the createAlertDialog function.

➤ ScollView: A ScrollView is a section within a window that you want to be able to scroll. It is limited in that it can scroll on only one axis at a time.

➤ ScrollableView: A ScrollableView is a container that holds one or more views that can be scrolled horizontally. This is a control you would use to represent page fl ips. It also has a built-in paging control that you can use to show the active page index.

➤ View: This is a basic container. It renders on a window, and holds all of your UI objects.

➤ WebView: This is a View that renders valid web content. It allows you to open local or remote content. It is not limited to just HTML; it can open PDF and SVG as well.

➤ Window: This is the highest level container. This is what is used to represent each individual pane of your application.

➤ CoverFlowView: This view creates a slideshow-style view for the images associated with it. It provides a horizontal scroll action by default that lets you cycle through your images.

➤ DashboardView: This view renders DashboardItem objects in a grid like the iOS main screen.

➤ OptionDialog: This view renders a modal to the user with a set of possible selections.

➤ EmailDialog: This view renders a modal containing the OS-specifi c send email layout.

c10.indd 293c10.indd 293 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

294 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

Basic UI Data/Layout Elements in Titanium

This section covers layout elements that are specifi cally for data sets and to organize views within your application.

➤ ButtonBar, TabbedBar, Toolbar: These elements are used to represent options that could be used on multiple panes. The ButtonBar element renders similarly to most bottom option bars on iOS applications. The difference between the ButtonBar and the TabbedBar is that the TabbedBar persists its state visually.

➤ Picker, PickerColumn, PickerRow: This element and its children are used to create the option picker UI element. By default it renders only a single piece of data per row, but by specifying picker columns in each picker row you can provide many different selectors. PickerColumns are items within the PickerRows that are children of the picker element.

➤ Tab, TabGroup: TabGroups are containers for tabs, and tabs contain windows. When using a TabGroup (while it is active), it is the main container for your UI.

➤ TableView, TableViewRow, TableViewSection: A TableView is the standard UI element for holding tabular data. The TableViewRows are its children, and the TableViewSection allows you to create headers for groups of rows.

➤ 2DMatrix, 3DMatrix: These objects hold values for affi ne transformation matrices. These are used to rotate, scale, and translate (and in 3-D, skew) the objects in a two-dimensional and three-dimensional space, respectively.

Debugging

The Titanium.API module provides lots of options for logging of events:

➤ Ti.API.debug(): Pass messages to the console that you want to treat as debug notes.

➤ Ti.API.error(): Pass messages to the console for error states.

➤ Ti.API.info(): Pass messages to the console for success or nondebug.

➤ Ti.API.log(): Pass messages to the console for custom severity issues.

➤ Ti.API.warn(): Pass messages to the console for when nonerror issues arise.

Titanium Studio is bundled by default from Titanium Mobile SDK 1.7 onward. It is an IDE that contains the build tools from Titanium’s original developer package and also has a very powerful debugger. Set a breakpoint and click the green bug to debug in the emulator of your choosing. Also, when running in debug mode, Titanium will break on uncaught exceptions or parse errors. The error messages are generally enough to get you in the right direction, but it can sometimes take a couple of passes to see what they are getting at.

CONNECTING TITANIUM TO THE MARKETS

You will need to have a Developer account for Apple and Android before deploying to the respective app markets. Signing up for an Apple Developer account is explained in Chapter 7, and signing up for Google Play Developer account is covered in Chapter 6.

c10.indd 294c10.indd 294 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Connecting Titanium to the Markets ❘ 295

In the Project Explorer window, depicted in Figure 10-10, right-click the project you want to deploy and select the appropriate deploy action.

To distribute a build to the iTunes App Store you will need to cut a release build. Just like building for development, an option is afforded you in the Titanium Studio interface (see Figure 10-11).

The fi rst four options of this form are outlined in Chapter 7. Next, you must select the SDK version in which you want your fi nal build to be compiled. After that it asks for your Distribution Certifi cate; this is stored in your keychain. The last option asks where you would like your compiled fi le to be stored after building.

Figure 10-11 shows the Distribute — App Store option.

To distribute a build to Google Play, you will need to cut a release build. Just like building for development, you are given an option in the Titanium Studio interface (see Figure 10-12). Your distribution location is the folder where you want your build to be saved. The keystore location is the place on your fi lesystem where the keystore fi le is saved. The keystore password is the password that you set up when creating your keystore.

This differs from the iOS fl ow in that you must also sign your application. A certifi cate will be generated based on your passphrase, and it will be tied to the App Id set up for the application. Changing the App Id of this application after market release will prevent application updates or maintenance.

Obtaining a key for your application requires the Java KeyTool program, distributed with the Android SDK; instructions for use are available at http://developer.android.com/guide/ publishing/app-signing.html#cert.

FIGURE 10-10: The Deploy menu

FIGURE 10-11: Setting up iTunes deploy

c10.indd 295c10.indd 295 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

296 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

Versioning Your App

Versioning your app is quite simple. Open your TiApp.xml fi le and update the version parameter (pointed out in Figure 10-13). This is not exposed in the graphical editor, so you will need to do this by hand. This number will also be used to update your app in the stores.

FIGURE 10-12: Setting up Android deploy

FIGURE 10-13: Version number in TiApp.xml

c10.indd 296c10.indd 296 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Building the Derby App in Titanium ❘ 297

Once this is set you are ready to begin building your application.

BUILDING THE DERBY APP IN TITANIUM

The same patterns explained in the native application chapters are used to develop the Derby Names application, only this time in Titanium. You create the UI, using some of the device features (GPS, Accelerometer), and communicating with the web service you created in Chapter 3.

Common UI Patterns

This section discusses the basic patterns in mobile applications: standard ways to represent data, make selections, navigation patterns, and display quick alerts to the user.

Tables

The Table UI element is the standard way to display data.

You can bind JSON objects directly to tables (as long as they have a title element):

var data = [{title:”Row 1”},{title:”Row 2”}]; var table = Titanium.UI.createTableView({data:data}); win.add(table);

Or you can bind arrays of TableViewRow objects. When you create a TableViewRow object you can assign other UI elements to the row as well:

function BindTeamsToTable(dataFromService) { var dataToBind = []; Ti.API.info(JSON.stringify(dataFromService)); for (var i=0; i<dataFromService.length; i++) { var leagueName = dataFromService[i].LeagueName; var rowToAdd = Ti.UI.createTableViewRow( { title: leagueName, //main field to be bound and rendered hasChild: true //Show child arrow } ); rowToAdd.addEventListener(‘click’, function(){ teamToSearch = this.title; derbyservice.getRoster(BindRosterForTeam, teamToSearch); tabGroup.setActiveTab(0); }); dataToBind.push(rowToAdd); } var table = Ti.UI.createTableView({height: 368, top: 0, data: dataToBind}); win2.add(table); }

c10.indd 297c10.indd 297 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

298 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

If you have large sets of data to bind, this table element will be your go-to UI to display the data to your users.

The Table UI element is signifi cantly different from the HTML table element, so please don’t confuse one with the other. Whereas modern web development frowns upon the use of tables for layout, using tables to display data in mobile applications is commonplace.

You can fi nd more examples in the Kitchen Sink; try running both the iOS version and the Android version simultaneously to see these differences.

Pickers

The picker UI object illustrates some of the differences between how Titanium generates UI elements for iOS versus Android.

By default, the iOS element represented by this picker is a spinner (a date picker in iOS), whereas in Android the element represented by this picker is, by default, a drop-down. Titanium handles this by adding the usespinner property to the create method for this picker, but here you run the risk of maintaining parity between look and feel inside your app versus look and feel consistent with the OS on which your app is running. Additionally, although you can add custom views to your rows of the picker in Titanium, they will not be rendered on the Android version.

var picker = Titanium.UI.createPicker();

var dataToBind = [];

dataToBind[0]=Titanium.UI.createPickerRow({title:’Nose’});

dataToBind[1]=Titanium.UI.createPickerRow({title:’Friends’});

//dataToBind[2]=Titanium.UI.createPickerRow({title:’Friend\’s Nose’});

//You can’t pick this.

picker.add(dataToBind);

Using a picker provides users a uniform way to enter data quickly.

Navigation (Back Stack) and Tab Groups

In iOS you need to have a back button on a child view. It is not only standard in the OS, it is expected. As stated in the Apple Human Interface Guidelines (http://developer .apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/

UIElementGuidelines/UIElementGuidelines.html):

c10.indd 298c10.indd 298 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Building the Derby App in Titanium ❘ 299

You can use a navigation bar to enable navigation among different views, or provide controls that manage the items in a view.

Use the title of the current view as the title of the navigation bar. When the user navigates to a new level, two things should happen:

➤ The bar title should change to the new level’s title.

➤ A back button should appear to the left of the title, and it should be labeled with the previous level’s title.

If users can navigate down a path, developers need to provide a simple way of going back up the stack. Additionally, navigation back up the stack may involve persisting state as well, so be sure to account for whether a given view’s state needs to be persisted when retracing a user’s steps through the navigation stack. In Android, the hardware back button and the OS persist state and the “back stack” for you. That being said, if you have a back button in your UI, make sure that it is not displayed when on an Android device, because it will be considered unnecessary and sloppy.

When using tab groups the standard UI layout differs between iOS and Android. iOS displays tabs inside apps on the bottom. There is generally a black background with some see-through icons, and the tab highlights blue when selected (either the background of the tab or the icon on top). In Android, the tab navigation is almost always rendered on the top, with black and gray being the colors used to represent active and inactive. This only goes to further demonstrate the need for the Android and iPhone project subdirectories, to distinguish device-based and OS-specifi c layouts.

var win1 = Titanium.UI.createWindow({ title:’Roster’, backgroundColor:’#fff’ }); var tab1 = Titanium.UI.createTab({ icon:’KS_nav_views.png’, title:’Roster’, window:win1 });

var win2 = Titanium.UI.createWindow({ title:’Derby Team Names’, backgroundColor:’#fff’ }); var tab2 = Titanium.UI.createTab({ icon:’KS_nav_ui.png’, title:’Team Names’, window:win2 });

tabGroup.addTab(tab1); tabGroup.addTab(tab2);

tabGroup.open();

c10.indd 299c10.indd 299 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

300 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

First you create your two basic windows, and bind them to tab elements. Once bound, you add those tabs to the group of tabs. This builds your clickable UI for you.

Modal Forms

Modal forms are most commonly used to break away from your UI while communicating with a third-party source. This could be authenticating with OAuth or OpenID, publishing content to a social network, or anytime you want to lock the UI for the user.

var modal = Titanium.UI.createWindow(); modal.open({ modal: true, //Set it as modal navBarHidden: true, //Hide the UI Chrome fullscreen: false //Make sure that it isn’t rendered full screen. })

The preceding code creates a new modal window. It will show up over top of the current window, and not display any of the standard UI for a window element.

Alerts

There is a lot to be said for the value of a simple alert modal. Calling one is simple. A straight Javascript:alert(‘message’); renders out as an OS native message. That being said, it is best not to have this as the only way to communicate data to app users, because alerts block the UI and prevent things from happening behind the scenes. And queuing multiple, successive alerts can potentially put your UI in a very unmanageable state. Tread with caution.

var message = “Greetings Program!”; alert(message);

You are also afforded the OptionDialog view for displaying alerts that require a response. The following code snippet shows how to create an alert that requires a response. Setting the cancel property to -1 denotes that there is no cancel action in the list of potential options:

var dialog = Titanium.UI.createOptionDialog({ title: ‘Trick Question - Did you walk to school, or buy your lunch?’, options: [‘Walked to School’,’Bought my Lunch’], cancel:-1 }); dialog.show(); dialog.addEventListener(‘click’, new function(e){ //e.index = index of option selected. });

Once you have built your user interface, you will need to bind data to it. The following options show the ways you can get data onto the device.

c10.indd 300c10.indd 300 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Building the Derby App in Titanium ❘ 301

Offl ine Storage

Offl ine storage refers to any data that you will persist on the device. It can be as simple as a property bag, storing key-value pairs, or updating resource fi les, or it can be as complex as a full SQLite database.

SQLite

Titanium provides the developer with an interface to store data. This is exposed through the Titanium.Database namespace. You can create a database programmatically, but I would recommend installing one from a SQLite script in your resources folder:

var db = Ti.Database.install(‘../derbygirls.sqlite’,’derbyGirls’);

Once the database is on the device, make standard CRUD calls using the SQLite syntax:

var teamName = ‘Lansing Derby Vixens’;

var rows = db.execute(‘SELECT * FROM DerbyNames WHERE TeamName=”’ + teamName + ‘”’);

var data = [

{title:’’ + rows.fieldByName(‘Name’) + ‘ - ‘ + rows.fieldByName(‘JerseyNumber’) + ‘’}];

var derbyNameTable = Ti.UI.createTableView({

data:data

});

var currentWindow = Ti.UI.currentWindow;

currentWindow.add(derbyNameTable);

If you do not need to store relational data sets, but still want to store large pieces of information or content, the option afforded to you is Isolated Storage.

Isolated Storage

In most mobile SDKs you are allowed a sandboxed area of the fi lesystem most commonly known as isolated storage. Titanium exposes this functionality through its Titanium.Filesystem namespace.

Reasons to use isolated storage would be to store resources downloaded remotely or saving large data sets outside of a database environment. The following code looks on the fi lesystem and if it fi nds it adds it to the specifi ed window.

for (var i = 0; i < derbyTeams.Length; i++) { var teamLogo = Titanium.Filesystem.getFile(derbyTeams[i].TeamId + ‘.jpg’); if (!teamLogo.exists()) { Ti.API.error(“We have not loaded a logo for this team yet.”); return;

c10.indd 301c10.indd 301 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

302 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

} else{ var logoItem = Ti.UI.createImageView( { image: teamLogo, height: auto, width: auto });

win1.add(logoItem); } }

Preferences and Settings

Using the Property Bag (Preferences and Settings) is the simplest form of offl ine storage available. It is mostly used for storing authentication tokens and default display parameters. With the Titanium.App.Properties namespace, you can persist these properties between application runs. The following code shows how to save and retrieve properties from the property bag.

//Setting the UserName Ti.App.Properties.setString(“username”,”derbyfan419”); //Getting the Hashed Password from Property Bag var hashedPassword = Ti.App.Properties.getString(“password”);

Storing lots of information on your device can be time-consuming and diffi cult to maintain, so often applications query data from a remote location. Web services provide an easy way to retrieve these sets of data.

Web Service

This section shows examples to query from the web service created in Chapter 3, discusses formatting the data to be read by Titanium, and describes some of the “gotchas” that occur in platform-specifi c calls to a web service.

JSON Is Your Friend

Chapter 3 discussed the technology used to create the web service, but — platforms aside — what you really need to wrap your head around is JavaScript Object Notation (JSON). JSON is a simplifi ed way to store your data in a serializable way over the wire, while still following the structure of the initial object. The service you use outputs JSON to parse in the app. A great resource to see how a JSON object is outlined is the Json Parser Online (http://json.parser.online.fr/), as shown in Figure 10-14.

c10.indd 302c10.indd 302 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Building the Derby App in Titanium ❘ 303

The JSON parser gives you a nice visualization of the object, and shows any parsing errors. Effectively an array of dictionaries (key-value pairs), a JSON object can provide you with an entire object graph with little overhead.

Something to note at this point: when building up URLs to send in an XHR request in Titanium for Android (at least as of Titanium version 1.7), you have to do some postprocessing to it before passing it to be sent. If you are building for iPhone, you don’t have to worry. The following code shows the call necessary to format these request strings for Android.

if (Titanium.Platform.name == ‘android’) { requestString = requestString.replace(/\s/g, ‘%20’); }

What follows is the odata object that holds the getData function. When retrieving data from the service, pass the parameters to it, parse the response as JSON, and then pass it to the successFunction callback to bind the data to the window:

function odata(){ this.getData = function (requestString, successFunction){ if (Titanium.Platform.name == ‘android’) { requestString = requestString.replace(/\s/g, ‘%20’); } var xhr = Titanium.Network.createHTTPClient(); xhr.onload = function () { var response = JSON.parse(this.responseText); var result = response.d.results;

FIGURE 10-14: Json Parser Online

c10.indd 303c10.indd 303 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

304 ❘ CHAPTER 10 GETTING STARTED WITH APPCELERATOR TITANIUM

//for some reason oData will return it both ways, in .d and .d.results if (result == null) { result = response.d; }

var gotData = new Date(); successFunction(result); };

xhr.onerror = function (e) { Titanium.UI.createAlertDialog({ title: ‘Error retrieving data’, message: ‘An error occurred retrieving data. Please try later.’ }).show(); Titanium.API.error(requestString); }; xhr.open(‘GET’, requestString); xhr.setRequestHeader(‘Accept’, ‘application/json’); var send = new Date(); xhr.send(); }

This class is included in app.js so that all other windows can call into it statically if necessary:

Titanium.include(‘network/odata.js’); var odata = new odata();

Next is the derbyservice class, which is also included in app.js:

Titanium.include(‘network/derbyservice.js’); var derbyservice = new derbyservice();

It provides the method calls in the views to get data to bind:

function derbyservice(){ var baseServiceUrl =

“http://derbynames.gravityworksdesign.com/DerbyNamesService.svc/”;

this.getAllNames = function (successFunction)

{

var serviceString = baseServiceUrl + “DerbyNames”;

odata.getData(serviceString, successFunction);

}

this.getTeamNames = function(successFunction)

{

var serviceString = baseServiceUrl + “Leagues”;

odata.getData(serviceString, successFunction);

}

this.getRoster = function (successFunction, leagueName)

{

var serviceString = baseServiceUrl +

c10.indd 304c10.indd 304 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info

Building the Derby App in Titanium ❘ 305

“DerbyNames?$filter=League eq ‘” + leagueName + “’”;

odata.getData(serviceString, successFunction);

}

}

Now that you have a way to get data, this section discusses using location to pare down or request data.

GPS

As more and more people get smartphones with built-in GPS devices, the call for location-based content, information, games, social media integration, and driving directions is expected. Titanium does provide access to the metal for talking with the GPS. The methods to access GPS are available in the Titanium.Geolocation namespace within Titanium Mobile.

Depending on your usage, the geolocation API allows you to set the accuracy of the GPS data returned. You are afforded multiple options: Best, Nearest Ten Meters, Hundred Meters, Kilometer, and Three Kilometers. It is best practice to set your accuracy to one of these options prior to accessing the GPS:

Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST;

The GPS also has an understanding of how far the device has moved, and triggers an update event when the threshold of the distance fi lter has been crossed. Distance Filter is a double, and it is in meters. Default, if nothing, is set to 0, which means GPS update events are continuously fi red.

Titanium.Geolocation.distanceFilter = 15.24; //50 Feet

To get the position as reported by the GPS, you must call the Geolocation function getCurrentPosition. It provides object location with the following properties: latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, speed, and timestamp. The location property contains the following subproperties: magneticHeading, trueHeading, accuracy, x, y, z, and timestamp. The following code shows how to query the current position of the device and check with the web service to see what teams are close to your location:

var cityToQueryBy = ‘Lansing’;

Titanium.Geolocation.getCurrentPosition(function(e)

{

var latitude = e.coords.latitude;

var longitude = e.coords.longitude;

var altitude = e.coords.altitude;

var accuracy = e.coords.accuracy;

var altitudeAccuracy = e.coords.altitudeAccuracy;

var heading = e.coords.heading;

var speed = e.coords.speed;

var timestamp = e.coords.timestamp;

//This turns your location into a human readable object

Titanium.Geolocation.reverseGeocoder(latitude, longitude, geolocationCallback);

c10.indd 305c10.indd 305 28/07/12 6:07 PM28/07/12 6:07 PM

www.it-ebooks.info