building custom arcgis server applications with javascript...

Post on 07-Nov-2019

12 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Building Custom ArcGIS Server Applications with JavaScript Level 4

E-Learning for the GIS Professional – Any Time, Any Place! geospatialtraining.com

Introduction to Mobile Application Development

E-Learning for the GIS Professional – Any Time, Any Place! geospatialtraining.com

Module Outline

• Mobile usage and statistics

• Many operating systems and devices

– iOS, Android, Windows

– iPhone, Android, Windows Phone, Blackberry

– Smartphones

– Tablets

• 3 types of mobile web applications

– Native, Web, Hybrid

• Skills for mobile web application development

3

Mobile Statistics

• 5.9 billion world mobile subscribers at end of 2011 (87% of world population)

– Strong growth in Chin and India (account for over 30% of world subscribers)

• 1.2 billion mobile Web users

– Asia is top region

– South Korea and Japan lead in mobile broadband penetration with 91 and 88%

respectively

• Mobile devices account for 8.4% of global website hits

– In U.S. 25% of web users are mobile only

• Mobile device sales rose in 2011 with smartphones showing strongest growth

4 Statistics from mobithinking.com

Mobile Platforms

• Many operating systems, many devices

• Android from Google

– Android runs on many devices

• iOS from Apple

– iPhone, iPad

• BlackBerry OS from RIM

– List of devices

• Windows Phone from Microsoft

• Others

– Symbian OS from Nokia, webOS from HP, more

5

3 Types of Mobile Application Development

Native applications

Web applications

Hybrid Solutions

6

Native Applications

• Specific to the mobile device it is run on

• Programmed using Objective C on the iPhone or Java on Android devices

• Can use all the phone’s features including the camera, geolocation, and user’s address book

• Do not need to be connected to the internet to be used.

• Can be distributed on the phone’s marketplace (e.g. Apple Store for iPhone or Ovi store for Nokia

handsets).

7

Native Application Development Process

• Language used depends on platform

– Objective-C, C, C++ for Apple iOS

– Java for Android and Blackberry

– C#, VB.NET for Windows Phone

8

Native Application Development Process

• Source code compiled

– Optimizes the performance of the app

– Generates an executable

• Images and other resources

– Packaged with the executable

• Result is a distributable package

– Suitable for app store

9 Images courtesy of Worklight

Native Application Development Process

• Native applications have

– Full access to the OS API

– Provides a wide range of services

• Location

• Local storage

• Camera

• Audio and Video

• Touch Screen, Keyboard

10 Images courtesy of Worklight

Advantages of Native Applications

• Better functionality

– Can use all features of the smartphone

• Camera, address book, geolocation, augmented reality, others

• Native apps do not need necessarily to be connected to the internet to be used.

– Can work in offline mode

• Native apps get good visibility with consumers because they are distributed through the

phone manufacturer’s app store.

11

Disadvantages of Native Applications

• Can restrict number of users that can be reached

– Not compatible with all handsets

– Has to be developed for each type of platform

• Third-party approval can also be another barrier.

– Wait for approval

– Don’t have control over the timing of distribution

• May require user to learn new skills

– Objective C

12

Web Applications

• Run in the phone’s browser

• Developed with HTML, CSS, and JavaScript

• Works across all devices, and ensures cross-platform compatibility.

• Same base code can be used to support all devices, including iPhone and Android.

• Can’t all mobile device features, such as the camera or geolocation.

• Can’t be deployed to the phone’s marketplace.

13

Web Application Development Process

• Run through mobile web

browser (i.e. Safari)

• No need for app store

• Doesn’t have access to all

mobile os functions

– Camera, Microphone,

Vibration, Location

14 Images courtesy of Worklight

Advantages of Mobile Web Applications

• Compatible across all platforms and devices.

– Has more reach

• Make use of existing web technologies, such as JavaScript and CSS

– Technical barriers to entry are low.

– Developers can use their existing skills

• Companies can also make use of mobile search to allow their consumers to find the app.

• Distribution not through phone’s store

– No third party approval required before release

– Site can be updated in real-time and changed without requiring sign-off by the mobile

provider.

15

Disadvantages of Mobile Web Applications

• Do not make use of the phone’s other features, such as the camera or address book

• Can’t be deployed to the phone’s marketplace.

16

Hybrid Applications

• Native application with embedded HTML

• Mix of native and web apps on the phone’s browser

• Cross-platform development with HTML, JavaScript, CSS while still having access to

phone’s features

• Selected portions of the app are written using web technologies.

• The web portions can be downloaded from the web, or packaged within the app.

• This option allows companies to reap all the benefits of native apps while ensuring

longevity associated with well-established web technologies.

• The Facebook app is an example of a hybrid app; it is downloaded from the app store

and has all the features of a native app, but requires updates from the web to function.

17

Hybrid Application Development Process

• Native source code joined with HTML source code

– HTML code accesses data from web server

• HTML source code becomes a “resource” (similar to images)

• Combined into a package

– Suitable for app store

18 Images courtesy of Worklight

Hybrid Application Development Process

• Best of both worlds

– Native access to OS specific functions

– Web based rendering with

• HTML, CSS, JS

• PhoneGap provides a bridge

19 Images courtesy of Worklight

Hybrid Applications Use a Bridge

• PhoneGap

• Two main tasks

1. Takes existing code base and deploys to multiple mobile platforms

2. Provides access to specific os functions for the mobile devices

20

JavaScript Frameworks for Mobile Development

• JavaScript libraries

– Provide user interface widgets

– emulate native widgets found in mobile applications

• Dojo Mobile

• jQuery Mobile

• Sencha

21

HTML5

• Support for richer web applications

• Top supported features on mobile devices

1. Video and Audio

2. Geolocation API

3. Offline web application support

4. WebStorage

5. CSS3 Selectors

6. 2D animations through Canvas element

• Compatibility matrix

22

Native, Web, or Hybrid?

• The decision to invest in an app or in a mobile website depends on the company’s target

audience and the functionality of the app.

• Companies also need to consider time, budget and resources to develop each solution.

23

Native, Web, or Hybrid?

24

In this Class?

• In this class we follow the Hybrid Application Development Process

25

Skills for Building Hybrid Mobile Applications

• HTML5

• CSS3

• JavaScript

• JavaScript Mobile Framework (Dojo in this class)

• PhoneGap

• Third Party APIs (ArcGIS Server API for JavaScript in this class)

• Understanding of mobile device specific functionality

26

Introduction to Mobile ArcGIS Server Development E-Learning for the GIS Professional – Any Time, Any Place!

geospatialtraining.com

Module Outline

• Introduction to Mobile Development with ArcGIS Server API for JavaScript

• Integrating the Geolocation API

28

Introduction to Mobile Development with

ArcGIS Server API for JavaScript

29

Introduction to Mobile Development with AGIS API for JavaScript

• AGIS API for JavaScript provides support for mobile devices

• Current support

– iOS 3+, Android 2.2+, Blackberry 6+

• Integrated with Dojox.Mobile

• Compact build

• Built-in gesture support

• Not the same as the ArcGIS API for iOS or Android

– Native iOS applications

30

Compact Build

• Compact build of AGIS API for JavaScript available

• Smaller footprint; downloads quickly

• Perfect choice for mobile applications

• Primary differences

– Compact build only loads objects that are needed

– Only 32 code modules (compared to 80 in the standard API)

• Use dojo.require to load modules not in the core 32 of the compact build

• Link to table of modules for compact and standard

http://help.arcgis.com/en/webapi/javascript/arcgis/help/jshelp_start.htm#jshelp/inside_compactbuild.htm

31

Referencing the Compact Build

• Just need to add the word ‘compact’ in your reference

32

Setting the Viewport Scale

• Use viewport meta tag in the <head> of your page

– Set initial scale to 1.0

– If you don’t set a width, Safari will use device-width when in portrait

– If you don’t set a height, Safari will use device-height when in landscape

33

Exercise

• Please complete the following exercise:

Creating Your First Mobile ArcGIS Server JavaScript Application

34

Integrating the Geolocation API

35

Geolocation API

• Part of HTML5

• Used to get the location of a mobile device

– GPS, cell tower triangulation, IP address

• Integrates well with mobile applications

• Most web-kit browsers support Geolocation http://www.w3.org/TR/geolocation-API

– Safari

36

Requesting Permission

• Built in security

• Requires explicit permission from end user

37

Geolocation API

• Integrate Geolocation API with AGIS API for JavaScript applications

• navigator.geolocation object

• Geolocation.getCurrentPosition()

– Returns the current location of the mobile device

• Geolocation.watchPosition()

– Track a location as it changes

– Callback method fired each time position changes

38

Geolocation API Code Example

39

Exericse

• Please complete the following exercise:

Integrating the Geolocation API with ArcGIS Server API for JavaScript

40

Introduction to jQuery Mobile for User Interface Development E-Learning for the GIS Professional – Any Time, Any Place!

geospatialtraining.com

Module Outline

• Introduction to jQuery Mobile

• Data Roles

• Pages and Dialogs

• Headers and Footers

• Toolbars

• Navigation Bars

• Content

• Mobile Controls (Buttons, Lists, Form Components)

• Using Codiqa

42

What is jQuery Mobile?

43

What is jQuery Mobile?

• User Interface system for mobile devices

• Works seamlessly across a broad array of devices

• Built on jQuery and jQuery UI

• Page transitions

• Core user interface widgets

44

Basic Template

• Start projects with a basic template file

• Includes links to

– jQuery Mobile stylesheet

– jQuery

– jQuery Mobile

– ArcGIS Server API for JavaScript

– <head> tag with a <meta viewport> tag for mobile devices

– HTML5 data roles for page, header, content

• Link to template

45

Data Roles

46

What are Roles?

• Attributes attached to HTML elements

– Define element behavior

– Use ‘data-role’

– Example: <div data-role=“page”>

• Many jQuery Mobile roles

– Page, header, content, footer, navbar, button, listview, slider, others

47

Roles

• Primary roles on a page are

– ‘page’ (main unit)

– ‘header’

– ‘content’

– ‘footer’

48

Pages and Dialogs

49

Pages

• Main unit in jQuery Mobile

• Typically divided into 3 sections

– header

– content

– footer

• Pages within a Page

• HTML5 doctype of data-role=“page”

– Inside a <div>

– Content of a page can be any valid HTML

– Often contain other data-roles

50

Linking Internal Pages

• Can link to pages within a page

• Use #<id>

51

Exercise

• Please complete the following exercise:

Internal Page Links

52

External Page Links

• Can also use standard links for

– External pages

– Dynamically generated content (PHP, .NET, etc)

• External link must be in same domain

– Cross-domain security

53

External Page Link Rules

• The destination must be a jQuery Mobile document.

• The destination must be hosted in the same domain.

• The destination must be a one-page document.

• If the destination URL is a folder (for example, /clients), the href attribute must end with

slash, href="/clients/".

• The target attribute should not be declared, as in target="_blank".

54

Absolute External Links

• Used to link to another site or document that does not serve jQuery Mobile content

• Define the full url

55

Page Transitions

• Transitions define how the application moves from one page to another

• Right to left by default

• Use data-transition=‘name’

– Slide (default) = right to left

– Slideup = bottom to top

– Slidedown = top to bottoom

– Pop = small point in middle to full screen page

– Fade = fades between old and new

– Flip = 2D or 3D rotation

56

Multiple Pages

• HTML page can contain multiple ‘pages’

– Accomplished by stacking multiple <div> tags with a data-role of ‘page’

– Need unique id for each page

• ID used for linking

57

Dialogs

• Different way to show a page

• Not full screen

• Looks like a popup box

• Modal box

– Must take some action with the dialog

before going back to main application

– Has a close button (X)

• Use data-rel=‘dialog’ inside link tag

58

Headers and Footers

59

Page Header

• Normally defined within <h1> tag

• Often used for navigation

– Can include buttons for moving between pages

– 3 sections (left, title, right)

• Left and right used for buttons

• Not mandatory but generally used

60

Page Header

• Toolbar at the top of the page

• Can contain a title and buttons

• Use <h1> HTML tag

• Themes with an ‘a’ swatch by default

– Can easily be themed though

61

Adding Buttons to a Header

• Space on left and right side of title for buttons

• Use <a> tag for creating buttons

• First button placed on left side and second on right

• Can also use predefined icons

– Use data-icon

62

Adding Buttons to a Header

• By default button color is same as toolbar theme

• Can use data-theme to change the color of individual buttons

• Can also insert a logo (image) instead of text

– Use <img> tag inside <h1>

63

Footer

• Similar to header but more flexible

• Use <a> element

• No specific left and right button placement

• Can add as many button as needed

• No padding between buttons

– Add ui-bar class for spacing

64

Exercise

• Please complete the following exercise:

Working with Headers and Footers

65

Toolbars

66

Toolbars

• Attached to headers or footers

• Can be positioned

– Inline (default)

– Standard fixed

– Full screen fixed

– True fixed

– Use data-position to define positioning

67

Inline Toolbars

• Default toolbar

• Fixed position

• Header/footer visibility controlled by scroll position

– Header only visible when scroll position near top

– Footer only visible when scroll position near bottom

68

Standard Fixed Toolbars

• Toolbars disappear while user is scrolling content

– Hidden with a fade transition

• Toolbars reappear when scroll stops

• Toolbars convert to inline mode when user taps content

• Use data-position=‘fixed’

69

Full Screen Fixed Toolbars

• Allows for full screen display of content and access to the toolbar when needed

• Hidden fixed toolbar

• Appears when user taps the screen

• Disappears when user taps the screen again

70

Navigation Bars

71

Navigation Bars

• Used for navigation purposes within a mobile application

• Up to 5 buttons with optional icons

• Unordered list of links within a container

– Container has data-role=‘navbar’

• Can activate a button

– class=‘ui-btn-active’

72

Navigation Bars as Tabs

• Can add navigation bars to a footer

– Simulate tabs

• Add ‘navbar’ to footer

73

Content

74

Collapsible Content

• Any HTML code will work inside <div data-role=‘content’>

• Mobile devices have limited space

– jQuery provides for collapsible content to make best use of space

– Content can be hidden or revealed

– Collapsible content should have header

– Use data-role=‘collapsible’

75

Collapsible Content

76

Accordion

• Component allows you to group content

– Only one panel visible at a time

– All other panels closed

77

Code Samples

78

Collapsible content

Accordion

jQuery Mobile Controls

Buttons, Lists, Form Components

79

Buttons

• Function similarly to <a> links but better….

– Provide a better interface for mobile users

– Larger so easier for the end user to click

• Renders as rounded button with centered label and shadows

• Created in several different ways

– Button element

– Input element with different types

• button, submit, reset, image

– data-role=‘button’

• Span the entire width of a content area by default

80

Inline Buttons

• Inline buttons created in a row

• Don’t use whole width

• Use data-inline=‘true’

81

Grouped Buttons

• Can group related buttons

• Horizontal or vertical

• Button group is inside a container (no space in between buttons)

– Container is a <div> with data-role=“controlgroup”

82

Button Icons

• Can add icons to buttons

• jQuery Mobile includes a set of commonly used icons

• Uses CSS Sprites to reduce image loading

• Use data-icon=“<icon_name>”

• Many icons

– Arrows, delete, plus and minus sign, checkmark, gear icon, refresh, forward and

backward, grid, star, alert, info, home, search

83

Icon Positioning, Icon Only Buttons, and Icon Shadow

• Icons render to left of button text by default

– Use data-iconpos=‘right’ to change

• Left, right, bottom, top

• Use data-iconpos=‘notext’ to create button without text

– Not normally done as icons are small

• Can remove shadow effect with data-iconshadow=‘false’

84

Lists

• Lists created using

– HTML list elements <ul>, <ol>, <li>

– Unordered is most typical <ul>

– data-role=‘listview’

• Frequently used in mobile applications

85

List Styling

• Lists stretch the entire width of the screen

by default

• Can also create inset lists

• Use data-inset=‘true’

86

Visual Separators

• Can divide a list into groups

• Use separators

– Use data-role=‘list-divider’

87

Interactive Rows

• Lists that contain <a> element

converted to interactive rows

– Useful for touch or cursor

navigation

– Whole row is interactive (can touch

anywhere)

• Adds an arrow to the end of the row

– Can change the default arrow icon

88

Nested Lists

• Lists for hierarchical data or drill-downs

– Country State Zipcode Census Tract Census

Block Group

• Embed a <ul> or <ol> inside a <li>

• Nested list rendered in a different theme

• No limit to number of levels

89

Split Button Lists

• Way of providing two actions from a single row

• Each section acts as a separate button

• Detail and edit sections are common

• Use two <a> elements inside a <li>

• Not necessary to add text to the second

– Use icon

90

Creating Images for Rows

• Can define one icon per row

– Two types

• Both types display image on left hand side of row

before the title

• Use <img> element

1. Icons

– 16 x 16 image

– Use for actions (delete, edit, etc)

2. Thumbnails

– 80 x 80 image

– Use for pictures, photos, graphical information

91

Row Titles and Descriptions

• A title can be added with a larger and bold font

• Description can be regular text

• Use header element (hx) for title and <p> element for description

92

Count Bubbles

• Useful for showing the number of items for a row

• Numeric information

• Use <span> tag with class ui-li-count

93

Exercise

• Please complete the following exercise:

Adding Lists to a Mobile Application

94

Filtering Data with Search

• Can provide a way of filtering a list when

user begins to type in Search box

• Add data-filter=‘true’ to <ul> or <ol>

– Adds a Search box

95

Form Actions

• Form actions handled as expected

– Form data submitted when button is clicked

• Can use get or post as action attribute

96

Form Element Information

• Support for standard web controls and new HTML5 controls in same form

• Each element can have a label

– Label tied to a control

• When user clicks the label it activates the associated control

• Field container is a wrapper for the label and component

– Improves user experience on tablet devices

– Use data-role=‘fieldcontainer’

97

Text Fields • Support for many types of text controls

– HTML5

– text, password, email, tel, url, search, number

– Email, tel, url, search, number are new with HTML5

• Keyboard changes based on the type of text control

98

Image courtesy of:

jQuery Mobil Up and Running

TextArea

• For controls that need to hold more than a line of text

• Auto-growing with jQuery Mobile TextArea

– Starts with 2 lines

• Grows when more space needed

99

Slider

• Used for numeric range data

• Sliding scale

– HTML5

• Attributes for

– Defining the min and max value (min, max)

– Initial value (value)

• Can be themed

100

Flip Toggle Switch

• Used for true/false values

• Use data-role=‘slider’

– Use ‘select’ element with two <option> elements

• One option for true and the other for false

101

Select Menus

• Allows end user to select one or more options

• Can be single or multiple selection

• Use <select> with multiple <option> elements

102

Radio Buttons

• Allows for the selection of one item from multiple options

• Each option has same name

• Can use data-role=‘controlgroup’ to group

items for better user interface

103

Check Boxes

• Similar to radio buttons

– Allow multiple selections

• Use <input type=‘checkbox’>

• Can use data-role=‘controlgroup’ to group

items for better user interface

104

Exercise

• Please complete the following exercise:

Capturing Information with Form Elements

105

Using Codiqa

106

Codiqa Builder

• Use Codiqa Builder for rapid user interface prototyping of jQuery mobile applications

• http://codiqa.com/builder

107

Codiqa Builder

108

Using JavaScript with jQuery Mobile

E-Learning for the GIS Professional – Any Time, Any Place! geospatialtraining.com

Outline

• The mobileinit() event

• Configuration Parameters

• jQuery Mobile Utilities

• Dynamic Content

• Event Handling

110

Introduction

• Best to create pages, widgets, and content with markup

– Control them with JavaScript

• jQuery Mobile also provides events you can respond to

• Configuration parameters

111

The mobilinit() Event

112

The mobileinit Event

• New event to handle for document loading

– mobileinit

• Fired when jQuery Mobile framework is loaded and ready for initialization code

• Handled on the document element

• Must be placed very specifically

– Between jQuery core include and jQuery Mobile include

113

Configuration Parameters

114

Configuration

• Several levels of configuration

– Global

– Page

– Widget

• New ‘mobile’ object attached to main jQuery object ($)

– Referenced as $.mobile

• Configuration parameters set off this object

115

Accessing Widgets for Configuration

• Widgets typically mapped with data-role attribute

– A few form controls don’t use data-role

• Widgets have object constructor and default configuration

– Access prototype for each widget placed on a page

• Syntax

$.mobile.<widget_name>.prototype

• Example

$.mobile.page.prototype

– Widgets have ‘option’ object where you can define default attributes

116

Global Configuration

• Can make global changes

– Affect every control in the application

– Use as a global parameter instead of defining a data-* role for every element

• Provides a more efficient way of coding when element parameters will be the same

– Example:

We want each page that has ‘history’ to contain a Back button in the header so that the

user can return to the previous page

117

Page Configuration

• Each page has default options that can be set in the mobileinit event

• Change defaults using page.prototype.options.<attribute>

118

Widget Configuration

• Each mobile widget has its own default configuration attributes

• Use following syntax

$.mobile.<widget_name>.prototype.<property>

• Each widget has specific default properties

119

jQuery Mobile Utilities

120

Utilities

• jQuery provides a number of utilities for managing an application

• Utilities provides through methods and read-only attributes

• Utility types

– Page Utilities

– Platform Utilities

– Path Utilities

– UI Utilities

121

Page Utilities

• Change page

– Very useful utilities for programmatically transitioning to another page

– Can be internal or external

– Detailed on the next slide

• Access the current page and id

• Current page container

– Normally the <body> element

122

changePage() Method

• Programmatically transition the application to a new page

– Page can be internal or external

• `External

• Internal

– Can define various options for the page

• Transition, Reverse, Type, Data, changeHash, data-url, others

123

Platform Utilities

• gradeA()

– Returns true if the browser is an A-grade browser on jQuery Mobile compatibility chart

• urlHistory

– Returns a collection of pages browsed without a page reload

– Contains an object with pageUrl, title, and transition

• getDocumentUrl()

– Original document URL (first loaded page)

• getDocumentBase()

– Original document base

• getScreenHeight()

– Current screen height

124

Path Utilities

• Path management utilities

– $.mobile.path

• parseUrl(url) – returns object with protocol, hostname, port, pathname, directory,

filename, hash

• makePathAbsolute(relativePath, absolutePath) - returns absolute path from relative

path

• makeUrlAbsolute(relativeUrl, absoluteUrl) - returns absolute URL based on relative

• isSameDomain(url1, url2) – returns true if both URLS are from same domain

• isRelativeUrl(url) – returns true if the URL is relative

• isAbsolute(url) – returns true if the URL is absolute

125

UI Utilities

• User interface utilities

– $.mobile.getInheritedTheme(element, defaultSwatch)

• Retrieves the color swatch that should be applied to an element based on its own color

swatch definition or the inherit chain.

– $.mobile.silentScroll(y)

• Scrolls to any position on the page without animation and event triggering

– $.mobile.showPageLoadingMsg()

$.mobile.hidePageLoadingMsg()

• Show or hide the loading message popup

126

Dynamic Content

127

Creating Pages on the Fly

• Mobile pages can be created on the fly with JavaScript

– Not recommended

– Can be done but CSS styling not included and if user reloads the page it won’t work

without a lot of work

– Better to create a template page containing the widgets you need and update these

widgets with dynamic content

128

Creating Widgets

• Can dynamically create widgets

– Each widget has a constructor

• Just use widget name as function call

$(“#list1”).listview() will convert a <ul> to a listview

129

Updating Widgets

• Can change content of existing widgets

• Common to initially create an empty list and then add content to the list later

• Have to refresh widget after changes

$(“#list1”).listview(‘refresh’);

130

Event Handling

131

Event Types

• Number of event types in jQuery Mobile

– Page Events

– Widget Events

– Orientation Event

– Gesture Events

132

Page Events

• jQuery Mobile application can have a number of different pages

– Loaded internally or externally

– Each page has different set of events that we can handle globally or individually

• Global event handling applies to all pages at the same time

• Use $(document).bind to handle page events globally

• Each page has different types of events

– Creation events

– Loading events

– Showing events

133

Handling Events

• Use $(document).bind

• Attaches the event handler to any current elements of the page

• At jQuery Mobile 1.7 a new ‘on()’ method is introduced

– Combines ‘bind’ and ‘live’

134

Page Creation Events

• Each page has its own creation or initialization events

– pagebeforecreate – after page is inserted into DOM but before widgets are created

– pagecreate – after page is created but before widgets are rendered

– pageinit – after page is fully loaded. Most used event for a page.

– pageremove – after page is removed from DOM

135

Page Loading Events

• Not all pages loaded by default with the first document

• Special event handlers for each page loaded using AJAX

• Bound to $(document)

• Available loading events

– pagebeforeload

• Fires before AJAX request is done

– pageload

• Fires after page loaded and inserted into DOM

– pageloadfailed

• Fires when page could not be loaded

136

Page Loading Events

• 2 parameters passed to page loading events

– Event object

• Typical event handling values

– Data object

• preventDefault() method

• Various properties

– url – absolute or relative URL as requested by $.mobile.loadPage

– options – options passed to $.mobile.loadPage

– textStatus – used for any sort of error message

– errorThrown – Error exception object valid with pageloadfailed

– Others (absUrl, dataUrl, xhr, deferred)

137

Page Showing and Hiding Events

• Pages are initialized once but can be shown or hidden many times

• Change page events and transition events related to showing and hiding

• Available page change events

– pagebeforechange

– pagechange

– pagechangefailed

• Available page transition events

– pagebeforeshow

– pageshow

– pagebeforehide

– pagehide

138

Page Change Events

• pagebeforechange – fires before the change is made and before any transition begins

• pagechange – fires after the change is done

• pagechangefailed – fires if page change could not be done

• Each event receives two arguments

1. toPage – Url of the destination page (or DOM object is page is internal)

2. options – options sent to $.mobile.changePage

139

Widget Events

• An updatelayout event fires when any widget that can show/hide content dynamically

has been updated

• May want to handle this event for UI purposes

140

Orientation Event

• Two mobile orientations: portrait and landscape

• The orientationchange event triggered when this changes

• Can include with <body> element

141

Gesture Events

• Touch events handled by jQuery Mobile

• Can be bound to any DOM element

• tap – fired when the user quickly touches the screen (like a mouse click)

• taphold – fired when user touches and holds the screen for one second

• swipeleft – fired when user swipes a finger from right to left

• swiperight – fired when user swipes a finger from left to right

142

PhoneGap Fundamentals

E-Learning for the GIS Professional – Any Time, Any Place! geospatialtraining.com

Module Outline • PhoneGap Fundamentals

• Installing PhoneGap and Using PhoneGap Build

• Referencing the PhoneGap API

• PhoneGap Events

• The Device, Network, and Notifications

• Accelerometer

• Compass

• Geolocation

• Media

• Camera

• Storage

• Files and Directories

• Contacts

• Capture

144

PhoneGap Fundamentals

145

PhoneGap Solves Problems

• Allows web developers to use HTML, JavaScript, CSS for mobile applications

• Access to mobile device features (camera, contacts, accelerometer, etc)

• Write the code once and deploy to multiple mobile platforms

146

What is PhoneGap?

147

What is PhoneGap?

PhoneGap + HTML/JS/CSS

iPhone

Android

Palm

Windows Mobile

Blackberry

Nokia

webOS

148

What is PhoneGap?

• Mobile development framework

• Write code once – deploy to Apple iOS, Android, webOS, Windows Mobile, Nokia

Symbian OS, BlackBerry

• Use native device functionality

• Uses HTML5

• Open Source projects extend this support to include Windows 7 and Mac OSX

149

How PhoneGap Works

• Mobile device platforms all different

– Same application must be re-written for each platform

• Doesn’t have to be that way

• Build your app once with web-standards

– Based on HTML5, PhoneGap leverages web technologies developers already know

best…HTML and JavaScript

– Author native applications with web technologies

• Wrap it with PhoneGap

– Use the free open source framework or PhoneGap build to access native mobile APIs

• Deploy to multiple platforms

– Uses standards based web technologies to bridge web applications and mobile devices 150

How PhoneGap Works

• HTML

• CSS

• JavaScript

Web Technology

• Dojo

• jQuery

JavaScript Frameworks • iPhone

• Android

PhoneGap

151

Development Pattern

Code Application HTML/JS/CSS/PhoneGap

PhoneGap Build Deploy

152

Installing PhoneGap and Using PhoneGap Build

153

Installing and Configuring PhoneGap

• www.phonegap.com

• PhoneGap can be installed on OS X, Windows, or Linux

• Need to download the version of PhoneGap that matches mobile development platform

you intend to support

– iOS

– Android

– Blackberry

– webOS

– Symbian

154

PhoneGap Build

• No need to download, install, and configure PhoneGap for each platform

• Use PhoneGap Build service instead!

• Submit your code and get back app store ready application!

• Saves time and effort particularly if you are going to support numerous device options

155

PhoneGap Build

• No need for SDKs, compiles and hardware

156

Write the Application HTML, JavaScript, CSS

Upload to PhoneGap Build

Mobile Device Ready Apps

PhoneGap Build

• Currently in beta (February 2012)

• No installation needed

• Free service for developers and open source projects

• Commercial projects

157

Referencing PhoneGap

158

Referencing the PhoneGap API

• Provide a reference to the PhoneGap JavaScript API

• Reference PhoneGap like any other JavaScript library

159

PhoneGap Events

160

What are Events?

• Any action that can be detected by PhoneGap

• PhoneGap has specific mobile events

– backbutton

– deviceready

– menubutton

– pause

– resume

– searchbutton

– online

– offline

161

The deviceready Event

• Very important!

• Fired when PhoneGap has fully loaded

• No other code should execute until this event is fired

• All applications should listen for this event

– Can cause problems if you attempt to execute before this event fires

162

PhoneGap Events

• menubutton

– Fires when user presses Menu button (Android)

• pause

– Fires when an application is put into the background

• resume

– Fires when a paused application is put back into the foreground

• searchbutton (Android)

– Fires when user presses the Search button (Android)

• online (iOS, Android, Blackberry)

– Fires when a PhoneGap application is connected to the Internet

• offline (iOS, Android, Blackberry)

– Fires when a PhoneGap application is not connected to the Internet

163

The Device, Network, and Notifications

164

Retrieving Device Information

• Obtain device specific information with the ‘device’ object

• Properties

– Name

• iPhone name is the name set in iTunes

– Platform

• Android, Blackberry, iPhone, webOS

– ID

• Unique ID of the device

– Version

• OS version

165

Getting Network Information

• Network information important for mobile devices

– Signal strength varies

– Can be cellular or WiFi

• Connection object

– Connection.type returns

• UNKNOWN

• ETHERNET

• WIFI

• CELL_2G

• CELL_3G

• CELL_4G

• NONE

166

Notifications

• Alerts

– Dialog box containing a message

• Confirmations

– Similar to an alert but may contain multiple buttons

• Beeps

• Vibrations

167

Accelerometer

168

Accelerometer

• Captures X, Y, and Z motion of the device

– Example:

• Moving to the left changes the X coordinate

• Moving forward changes the Y coordinate

• Z is an elevation value

• API uses an acceleration object

169

Acceleration Object - Properties

• Read-only object

• Contains data captured at a specific point in time

• Properties

– x

– y

– z

– timestamp

170

Acceleration Object - Methods

• Several methods

– getCurrentAcceleration()

• Gets current acceleration object at a point in time

– watchAcceleration()

• Collects acceleration data at a regular interval

• Accepts a frequency option (how often to collect) specified in milliseconds

– clearWatch()

171

Compass

172

Compass

• Obtains the direction the device is pointing

• Returns a heading

– 0-359.99 degrees

– Corresponds to direction

• Uses magnetic field sensors

• Compass varies depending upon device

– Look different but provide same information

173

Compass Object and Methods

• Compass object has several methods

• getCurrentHeading()

– Gets the heading at a specific point in time

• watchHeading()

– Gets the heading at a regular interval

• clearWatch()

– Stops processing of watchHeading()

174

Compass Example

175

Geolocation

176

Geolocation

• Geographic location of the device

• Most commonly uses an internal GPS (can use other methods too)

– Determines latitude/longitude coordinates of device

• Methods other than GPS (less accurate)

– IP address

– RFID

– WiFi Media Access Control address

– Cell Tower Triangulation

177

Geolocation Methods

• Primary methods

– getCurrentPosition() and watchPosition()

• Both can accept geolocation options

– frequency

• How often to retrieve geolocation data (in milliseconds)

– enableHighAccuracy

• Used to retrieve highest possible results

– timeout

– maximumAge

• Position is cached up to specified age (time) – in milliseconds

178

Geolocation Objects

• 3 read-only objects

– Position

– PositionError

– Coordinates

• Coordinates object is attached to Position

– This is the Coordinates object

• Objects are created using getCurrentPosition() and watchPosition()

179

Position

Coordinates

Position Error

Position and Coordinates Objects

• Created with geolocation.getCurrentPosition()

• Position properties include

– Coordinates object

• latitude/longitude

• accuracy

• altitude/altitudeAccuracy

• heading

• speed

– timestamp

• Passed into success callback function

180

PositionError

• Error callback from geolocation.getCurrentPosition() returns PositionError

• Contains error code and error message

• Error codes

– PositionError.PERMISSION_DENIED

– PositionError.POSITION_UNAVAILABLE

– PositionError.TIMEOUT

181

Media

182

Media

• Media refers to the ability to record and play back audio

– Audio files can be loaded on the device or streamed from web

• Media object

– Three parameters

• src

– URL to the audio file

• mediaSuccess

– Callback function triggered on completion of audio file play, record, or stop action

• mediaError

– Callback function for any errors

183

Media Methods

• Methods for

– Getting the current position in the audio file

• getCurrentPosition()

– Getting the duration of the audio file (milliseconds)

• getDuration()

– Play, pause, or stop an audio file

• play(), pause(), stop()

– Start an audio recording

• startRecord(), stopRecord()

184

Handling Media Errors

• Errors returned in MediaError object

– Contains

• Code

– MediaError.MEDIA_ERR_ABORTED

– MediaError.MEDIA_ERR_NETWORK

– MediaError.MEDIA_ERR_DECODE

– MediaError.MEDIA_ERR_NONE_SUPPORTED

• Message

185

HTML5 Audio Element

• HTML5 introduces a new <audio> element

– Used to playback existing audio files

– Take advantage of native browser player controls

• The ‘controls’ attribute adds interactive playback controls such as play/pause, time,

volume controls, position slider

• The ‘src’ attribute is a URL to the audio file

186

Camera

187

Camera

• Uses the built in camera of the mobile device

• Cameras vary greatly by device

• Photo gallery is a repository of pictures

• PhoneGap API provides a Camera object

188

Camera Object

• Camera object used for taking pictures and interacting with photo gallery

• One method

– getPicture()

• Options

– sourceType

» PHOTOLIBRARY or SAVEDPHOTOALBUM

» CAMERA

– quality

– destinationType

– allowEdit

– Success callback function receives a CameraSuccess object

189

Storage

190

Storage

• HTML5 storage options

– Not a device specific capability

• Not all mobile devices support HTML5 storage

– PhoneGap fills the void

• PhoneGap supports

– Web SQL databases

• Complex data storage requirements

– Local or session storage option

• Simple data storage requirements (key/value pairs)

191

Session or Local Storage?

• Session storage holds data in memory while the browser window is open

– Data is deleted when browser closed

• Local storage persists data between browser sessions

• Storage should be limited to 5 MB

192

LocalStorage Object

• Use LocalStorage when storing simple datasets such as key/value pairs

– Similar to a dictionary or has table

• Accessed from window object

• 5 methods

– key()

– getItem()

– setItem()

– removeItem()

– clear()

193

Database Object

• Used to store more complex data

– Multiple columns of data (not just a single key/value pair)

• Web Database (SQLite) database

• Accessed from window object

– dbName = Database name

– version = Database version

– displayName = Display name of database (user friendly)

– size – Size in bytes

194

Running a SQL Query

• Use SQL syntax to query

• Use executeSQL method

• Can retrieve data, create tables, insert rows

• Can also use transactions for running multiple statements

195

Transactions

• Used to execute multiple SQL statements as a batch

• database.transaction(transact_function, error, success) method

– The transact_function contains individual SQL statements

• SQLResultSet returned to success callback function

196

Viewing a Result Set

• SQLResultSet returned to success callback function

– From transaction() or executeSql()

• Properties

– insertId

• Row ID of the inserted row

• Only applies to insert statements

– rowAffected

• Number of rows changed with an update

– rows

• SQLResultSetRowList of rows returned

197

Error Handling

• SQLError object

• Properties

– code

• SQLError.UNKNOWN_ERR

• SQLError.DATABASE_ERR

• SQLError.VERSION_ERR

• SQLError.TOO_LARGE_ERR

• SQLError.QUOTA_ERR

• SQLError.SYNTAX_ERR

• SQLError.CONSTRAINT_ERR

• SQLError.TIMEOUT_ERR

– message

198

File and Directories

199

Filesystems

• All mobile devices have a filesystem

• PhoneGap provides limited access

• Filesystem object

– Properties

• name

– Filesystem name

• root

– Root directory of filesystem

– Contains DirectoryEntry object.

• Use window.requestFileSystem() to access

200

Directories and Files

• Filesystems contain directories and files

– DirectoryEntry

• Directories

– FileEntry

• Files

201

DirectoryEntry Object - Properties

• DirectoryEntry

– Properties

• isFile (always false)

• isDirectory (always true)

• name

• fullPath

– Path from the root to DirectoryEntry

202

DirectoryEntry Object - Methods

• Contains methods for

– Moving and copying directories

• moveTo() and copyTo()

– Removing directories

• Remove() and removeRecursively()

– Getting file and directory objects

• getFile() and getDirectory()

– Metadata

• getMetadata()

203

FileEntry

• Methods

– Moving and copying

• moveTo() and copyTo()

– Removing

• remove()

– File

• file()

– Creating a File

• createWriter()

• Properties

– name, fullPath

204

Reading Files

• Use FileReader object

– Text or Base64-encoded data string

• Create new instance of FileReader

• Call readAsText(file) passing in a file

object

– Reads text files

• Call readAsDataURL(file) to read

binary files such as images

205

Writing Files

• Use FileWriter object

– One for each file

– Maintains

• File position

• Length attributes

• Can seek and write anywhere in

the file

• By default writes to beginning of

file

– Overwrite existing data

– Use ‘append’

» Writes to end of file

206

Contacts

207

Introduction to Contacts

• All mobile devices have a contacts database

– Family, friends, business associates, etc

– Not all devices have the same attributes for contacts

• PhoneGap handles the differences

• Use Contacts API

208

Creating Contacts

• Use create() method

• Can set properties of a contact

– Name, displayName, nickname, phoneNumbers, emails, addresses,birthday, others

– Can use various objects

• ContactField, ContactName, ContactAddress, ContactOrganization

209

Saving a Contact

• Once created a Contact can be saved

• Call Contact.save(onSuccess, onFail)

210

Removing a Contact

• Use remove() method

– Contact.remove()

• Can pass optional success and failure callback functions

– Contact.remove(onSuccess, onFail);

211

Finding a Contact

• Use Contacts.find() method

• Parameters

– contactFields

• Set of Fields returned from the find operation

– onSuccess

• Passed a Contact object containing the fields requested

– onError

• Any error message

– options

• Filter option is a string to query the Contacts database

212

Finding a Contact

213

Capture

214

Capture

• Capture API

– Video

– Audio

– Photos

215

Capturing Video

• Use device.capture.captureVideo() method

• Options argument can contain

– Limit – maximum number of video clips that can be captured (default is 1)

• Not supported on iOS (1 only)

– Duration – maximum duration in seconds

• Not supported on iOS, Android, or Blackberry

– Mode – recognized video capture mode (video/quicktime, video/3gpp, etc)

• Not supported on iOS, Android, or Blackberry

• Success callback function is passed the captured video

– Array of MediaFile objects

• Each describes the video clip 216

Capturing Video Code Example

217

HTML5 Video Element

• HTML5 <video> tag

• Used with an existing video file

• Use ‘src’ attribute to define URL to the video

• Controls attribute adds user interface widgets

– Play/pause

– Volume control

– Time code

– Position slider

218

Capturing Audio

• Similar to Media API

– Capture API can capture more than one clip at a time

• Use captureAudio() method

• Options

– Limit – number of audio clips to capture

• Not supported by iOS

– Duration – maximum duration of audio clips

• Not supported by Android or Blackberry

– Mode – selected audio mode

• Note supported by iOS, Android, or Blackberry

219

Capturing Audio Code Example

220

Capturing Images

• Similar to Camera API

• Allows you to capture more than one image and save them

• Use captureImage()

• Options

– Limit – number of images to capture (default is 1)

• Not supported on iOS (1 only)

– Mode – selected image mode (such as image/jpeg)

• Not supported on iOS, Android and Blackberry

221

Exercise

• Please complete the following exercise:

Integrating PhoneGap in Mobile Applications

222

Exercise

• Please complete the following exercise:

Using PhoneGap Build

223

Mobile Application Installation and Offline Access

E-Learning for the GIS Professional – Any Time, Any Place! geospatialtraining.com

Introduction

• Cover three topics in this module

– Creation of offline applications

– Offline data storage

– Installation of mobile applications

• Mobile applications don’t always have network access

• Use HTML5 Application Cache (Offline API) to create offline applications

• Application installed on mobile device

• Offline API not supported on all mobile devices

– Check compatibility at http://mobilehtml5.org

225

Outline

• The HTML5 Manifest and Offline API

• HTML5Offline Storage

• Icon Installation

226

The HTML Manifest and Offline API

227

Package Definition

• Package is list of files downloaded by the browser

• Must include

– Anything we want to be able to access offline

• JavaScript, HTML, CSS, jQuery Mobile files, images, other resources

228

HTML Manifest

• List of files (package) is compiled into a text file called a cache manifest

– Text file (offline.appcache)

• Served as MIME type text/cache-manifest

– First line in the file must be ‘CACHE MANIFEST’

– Then provide a list of URLs to the files

– Main HTML file is implicit (index.html, main.html)

– Comment lines start with #

229

HTML Manifest Sections

• Manifest can be sectioned

• Sections defined by a line ending with a colon

230

HTML Manifest

• Main application file needs to load the manifest

• Use the ‘manifest’ attribute in the <html> element

231

Downloading the Manifest File

232

Compatible Browser?

Download Manifest File

Valid MIME Type?

Start Download Process

(background)

All files downloaded?

Files stored locally

Important Point

• After download is successful the application is sandboxed offline

• Can’t access any online resources not originally defined in the manifest

• Solution:

– Create special section in manifest called ‘NETWORK:’

• Files defined in NETWORK section must be accessed online each time

– Must have Internet connection

233

Fallback Section

• FALLBACK section defines files to use when a resource is inaccessible

• Two values per line separated by a space

– First value is request URI to match

– Second value is the resource sent upon matching

• Cached for offline use

234

Updating Resources

• How to update files already downloaded to the mobile device?

• Background process will always try to get an updated manifest file from server

– No Internet connection

• Use current local version

– Internet connection

• Browser compares old manifest to new manifest

• ANY changes result in the entire manifest being reloaded

– Must have some sort of change though…if files names are all still same then no

updating occurs

– Common to have a comment line with last date/time of update.

» This triggers the loading

235

JavaScript applicationCache Object

• Can use applicationCache object to check status of application cache

• applicationCache.status property returns a value

– 0 = UNCACHED (first time the application has been loaded)

– 1 = IDLE (cache is idle)

– 2 = CHECKING (local manifest file being checked against server manifest file)

– 3 = DOWNLOADING (resources are being downloaded)

– 4 = UPDATEREADY (update was downloaded but not available until next load)

• applicationCache.update() – forces an update check

• applicationCache.swapCache() – swap from old resource cache to new

– However, must make a full reload to see new resources

• history.reload() – Reloads new resource in the browser

236

JavaScript applicationCache Events

• Various events that we can handle

– checking – browser checking the manifest

– downloading – browser downloading resources in manifest

– progress – fired for each resource downloaded

– cached – download process has finished

– noupdate – no manifest update available

– updateready – update, new resources downloaded, waiting for reload

– error – error downloading a resource

– obsolute – manifest no longer valid, webapp deleted from storage and will not be offline

next time

237

Offline Storage

238

HTML5 Offline Storage Types

• HTML5 storage types

– sessionStorage

• Data stored for duration of the session

– localStorage

• Persistent until removed by application or user

• Data stored by one domain NOT accessible from another domain

• Several types: simple key/value pairs, file storage, SQL database stores

239

Using localStorage

• Accessible through window object

• Not all browsers support offline storage

– Use JavaScript function to detect support

– If browser does not support then use PhoneGap

240

localStorage Methods

• setItem(key, value) – saves or updates a value based on a key

• getItem(key) – gets a value based on a key

• removeItem(key) - removes a key/value pair

• clear() – clears all key/value pairs

• length – number of keys in a data store

241

Icon Installation

242

Introduction

• User can add icon for application to home screen

– Must be invited

– Opens application from shortcut instead of typing URL

• Icons have name, title, and definition

243

Invitation

• Users must be invited to install the application icon

• Mobile device platforms don’t allow automatic icon installation

244

Icon Name

• Each icon has a name

• Should be short since it will be displayed with the icon

– By default will be defined by <title> HTML element

– Displayed below icon

– Not much real estate in a mobile application

245

top related