facebook google plus twitter
Webucator's Free jQuery Mobile Tutorial

Lesson: Integration with the Phone

Welcome to our free jQuery Mobile tutorial. This tutorial is based on Webucator's jQuery Mobile course.

We can leverage many useful capabilities on mobile devices - capabilities that don't exist, in quite the same way or at all, on desktops - when building sites for phones: making a call, sending a text message, exploiting our current location, and other mobile-specific features. We can also customize our sites and apps for phone by adding icons appropriate for bookmarks and home screens. These strategies aren't strictly jQuery Mobile-based but fit in nicely with web development aimed at phones.

Lesson Goals

  • Learn how to present links for making phone calls, sending emails, and sending texts.
  • Learn how to add home screen/bookmark icons appropriate for mobile devices.
  • Learn how to use the Geolocation API to find the user's location.
  • Learn how to present video on mobile devices.

Calls, Emails & Texts

Links or buttons that open the mobile device's phone, email, or SMS-text application are easy to create. The traditional mailto: link works fine on phones, while tel: and sms: generate calls and texts, respectively:

Call, Email & Text Links
Type Markup
Phone Call <a href="tel:1-123-456-7890">Call 123-456-7890</a>
Email <a href="mailto:name@example.com">Email name@example.com</a>
Text Message <a href="sms:1234567890">SMS 123-456-7890</a>

Apple recommends the format 1-xxx-xxx-xxxx for US-based phone numbers.

In this quick example, we add "contact us" information for a page on the Nan & Bob's site, helpfully presented to users as three buttons - one each for calling, emailing, and texting:

call, email, text

Open IntegrationPhone/Demos/callemailtext.html to view the code and test the page on a mobile device. Note that the "call" and "text" links won't work on an iOS simulator.

Code Sample:

IntegrationPhone/Demos/callemailtext.html

We present each link as a button (with class ui-btn), using tel: for the phone button, mailto: for the email button, and sms: for the text button.

Custom Home Screen/Bookmark Icons

iPhone and other devices offer users the ability to add a shortcut/bookmark to a webpage on their home screen; our job as developers is to provide a custom icon that best represents our site or page. Including a line of code in the head of each page or including a specifically named icon in the website's root directory provides the functionality on iPhones and iPads; similar strategies work on Androids and other phones.

iPhone/iPad

  1. Place a PNG icon named apple-touch-icon.png in the website root directory to specify the icon for the entire site if you don't want to add a link tag to pages.
  2. Instead of adding an image to the website root directory, you can instead add a link element to the head section of any page to specify an icon for a single page:
    <link rel="apple-touch-icon" href="/custom_icon.png"/>
  3. To support different device resolutions (iPad vs. iPhone, for instance), add a size attribute to each link element:
    <link rel="apple-touch-icon" href="touch-icon-iphone.png">
    <link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
    <link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
    <link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">
    The icon that is the most appropriate size for the device is used. If no sizes attribute is set, the element's size defaults to 60 x 60.
  4. If there is no icon that matches the recommended size for the device, the smallest icon larger than the recommended size is used. If there are no icons larger than the recommended size, the largest icon is used.
  5. If no icons are specified using a link element, the website root directory is searched for icons with the apple-touch-icon... prefix. For example, if the appropriate icon size for the device is 60 x 60, the system searches for filenames in the following order:
    1. apple-touch-icon-76x76.png
    2. apple-touch-icon.png

See the Apple Developer site for full details.

Android

Android-Specific JSON Manifest

Since Chrome version M31, the mobile browser running on Android devices, Google has offered a way to set up a web app to have an application shortcut icon for adding to the device's homescreen; when clicked, the homescreen icon will launch the web application in full-screen "app mode". Since Chrome version M39, Google offers a way - via a JSON manifest - to specify metadata for the application, allowing us as developers a way to more closely mimic a native-application experience with our web app. You can find more details at https://developer.chrome.com/multidevice/android/installtohomescreen.

Homescreen-installed web apps work just like a "normal" web app, but integrate into the Android environment in the following extra ways:

  1. Installs Directly to Homescreen: users clicking "Add to homescreen" will see the app being added on to the homescreen.
  2. Integrates Into OS Task-Switcher: launching a web app from the homescreen means the app will appear in the task switcher, separately from the browser.
  3. Runs in Full Screen: Web apps run in full screen more, with no vestiges of a browser; the URL does not appear, nor browser elements like bookmarking and navigation controls.
  4. Supports a Default Device Orientation: Web apps launch and remain in the designation orientation (landscape or portrait).
  5. Navigating to External Pages Highlights Them to User: Users will always know if the web app routes them to a location outside the application's domain - especially useful for authentication flows, as the user is kept in the app experience but the URL of the authentication system is clearly visible to the user.

The JavaScript manifest, in JSON format, allows us to define things like a set of icons (various icons, for differing size and screen densities), a default orientation, a title, and landing page for our web app. To link to the manifest, simply include a link tag in the head of the web page, like this:

<link rel="manifest" href="manifest.json">

A typical manifest file might look like this:

{
	"name": "Sample Webucator Android Web App",
	"icons": [
		{
			"src": "launcher-icon-0-75x.png",
			"sizes": "36x36",
			"type": "image/png",
			"density": "0.75"
		},
		{
			"src": "launcher-icon-1x.png",
			"sizes": "48x48",
			"type": "image/png",
			"density": "1.0"
		},
		{
			"src": "launcher-icon-1-5x.png",
			"sizes": "72x72",
			"type": "image/png",
			"density": "1.5"
		},
		{
			"src": "launcher-icon-2x.png",
			"sizes": "96x96",
			"type": "image/png",
			"density": "2.0"
		},
		{
			"src": "launcher-icon-3x.png",
			"sizes": "144x144",
			"type": "image/png",
			"density": "3.0"
		},
		{
			"src": "launcher-icon-4x.png",
			"sizes": "192x192",
			"type": "image/png",
			"density": "4.0"
		}
	],
	"start_url": "index.html",
	"display": "standalone",
	"orientation": "portrait"
}

Our sample manifest includes references to various PNG icons - in assorted sizes and pertaining to specific screen densities - as well as a starting URL, display mode ("standalone"), and orientation ("portrait").

For mobile versions of Chrome on Android older than M39 but since M31, Chrome supports the following meta tag for homescreen-installed apps:

>meta name="mobile-web-app-capable" content="yes">

The Geolocation API

One can easily see the value of location-aware websites; increasingly, we rely on our phones to find the nearest gas station, restaurant, or shopping center. As we move through this lesson, we will explore how location-aware code might enhance the user experience for visitors to the Nan & Bob's site.

The World Wide Web Consortium (W3C) has worked to standardize a system by which developers can retrieve a user's location. Based in part on Google Gears, the API is now widely supported (see below for specifics) and offers a device-independent system for accessing the user's latitude and longitude via JavaScript.

How It Works

The GeoLocation API can find a user's location from a variety of information sources, using the best available. The W3C specification states:

The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. [From dev.w3.org/geo/api/spec-source.html#introduction]

If GPS is available, it will be used (though some devices, because of the delay and high energy use of GPS, opt not to use GPS). If GPS is not available, A-GPS (Assistive GPS, triangulated from cellphone towers), WiFi, IP, or another less accurate means of locating the user will be used.

Browser & Device Support

The W3C Geolocation API works for the following desktop and mobile browsers:

Geolocation API Supported Browsers
Platform Browsers
desktop Firefox from version 3.5 Opera 10.6 Google Chrome Internet Explorer 9.0 Safari 5
mobile Android (firmware 2.0 +) iOS Windows Phone

JavaScript Implementation

For devices that support the GeoLocation API, no external JavaScript file needs to be linked - the JavaScript functionality is inherent in the browser itself. The core of the code is the geolocation object, a child of the navigator object:

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, failureFunction, {enableHighAccuracy:false, maximumAge:30000, timeout:27000});
}

The if statement tests if the navigator.geolocation object exists on this device/browser. If so, we call the object's getCurrentPosition function - the first two parameters refer to a function (which we've called successFunction, but we could have used any name) to call when getCurrentPosition is successful in finding the user's location, and a function (failureFunction, in this example) to call when getCurrentPosition was not successful in finding the user's location; this parameter is optional. Both failureFunction and successFunction are functions we will write to handle the success and failure cases. The third parameter, a JSON-formatted hash of options, allows fine control over implementation details; we will omit this optional parameter when calling getCurrentPosition.

A Simple Example

Let's look at a simple page (IntegrationPhone/Demos/mapping.html) that pops up a JavaScript message with the user's latitude and longitude location. Users who visit our page will be prompted to explicitly allow our page to use their current location; see the left screenshot below. If they accept, our page will respond with their latitude and longitude, as on the right.

two iphone screenshots - geolocation example

Code Sample:

IntegrationPhone/Demos/mapping.html

Code Explanation:

We test, with an if statement, for the presence of the navigator.geolocation object; if so, we call the getCurrentPosition function. We write two functions, locateSuccess and locateFail, to handle the success and failure cases, respectively.

On successful finding of the user's location, function locateSuccess is invoked. Note that, as discussed above, we can name this function anything we like (though, of course, a meaningful name containing "success" makes sense here), as long as the name of the function is the same name we use for the first parameter of the getCurrentPosition function. The loc parameter exposes a variety of information about the user's location; we assign loc.coords.latitude and loc.coords.longitude to two local variables, and show those values to the user in a JavaScript alert (popup) window.

If the user's location is not found, function locateFail is invoked. We use a JavaScript switch statement to evaluate parameter geoPositionError's code property: if 0, something unknown happened; if 1, the user denied permission; etc.

Of course, we could extend this application extensively: we might use Google's Places library to allow the user to perform a search for "bookstores" and to return human-friendly addresses (hopefully Nan & Bob's!), rather than latitude and longitude. Check out the Google Maps Demo Gallery for some inspiration and code samples.

The parameter passed to the success function, which we named loc in our example above, exposes a useful set of properties:

Position Properties
Property Units
coords.latitude degrees
coords.longitude degrees
coords.altitude meters (may be null)
coords.accuracy meters
coords.altitudeAccuracy meters (may be null)
coords.heading degrees clockwise (may be null)
coords.speed meters/second (may be null)
timestamp a date and time

Finding Nearby Places

In this example, we'll make use of the free GeoNames service - specifically their Find nearby Wikipedia Entries service. We'll find the user's location as we did above, pass the latitude and longitude to GeoNames, and receive back a JSON-formatted list of nearby places' Wikipedia entries, which we use to populate a listview:

places demo

We can imagine that Nan & Bob, being community-minded folks, might want to allow visitors to their new site to find information about nearby places of interest - we'll add a button to the first page of this demo that allows users to find their current location then to see a short list of nearby points of interest. Users can click to read more on Wikipedia. Open up IntegrationPhone/Demos/places.html to test it out and to view the code.

Code Sample:

IntegrationPhone/Demos/places.html

Code Explanation:

This site comprises two pages: the home page and a page to display the returned results as a listview. Note the empty listview (an unordered list with id placelist) on the #places page.

We add a jQuery event handler to listen for clicks on the "Find Stuff Near Me" button - the button with id findme. When clicked, we call navigator.geolocation.getCurrentPosition that, if successful (the device supports it, user has approved the request to find his/her location, a location was returned), calls function locateSuccess. The locateSuccess function, in turn, calls function geonames.search.

Function geonames.search, which we define as part of namespace geonames, uses the jQuery function $.getJSON to retrieve a JSON-formatted list of places from GeoNames by passing a correctly formatted URL (with values for lat and lng, as defined by GeoNames, as well as parameters style, radius, and maxrows) - we found all of the details for this from the GeoNames website.

The next block of code iterates over the results returned from $.getJSON: we create an empty list item, append to it the data for each place record, and append the constructed list item to the placelist listview. We refresh the listview and change to the #places page for the user to view the results. Note that we use here the jQuery core iterator $.each - useful for looping over any sort of JavaScript collection, in this case a JSON result set. See the jQuery docs for more information on $.each.

Finding Weather Data

Nan & Bob would like to offer visitors to their website the opportunity to view weather conditions where they are. (We suggested showing the weather at the store, rather than the website-vistor's location - but hey, it's their site.) In the next exercise, you will make use of another GeoNames service (findNearByWeatherJSON) that returns the local weather conditions when supplied a latitude and longitude.

For this exercise, you'll need to use the jQuery iterator each, which you saw in the previous demonstration:

$.each(obj, function(i, val) {
alert(i + ' - ' + val);
});

If obj were a valid object (like the one that will be returned by the findNearByWeatherJSON service), then the code above would generate an alert for each name/value pair, with i as the field name and val as the field value. Note that this is slightly different from the earlier example: here were are iterating over the fields of the object, whereas before we were iterating over multiple objects.

Retrieving Weather Data

Duration: 25 to 35 minutes.

In this exercise, you will allow visitors to the Nan & Bob's site to find weather conditions for their current location. The result will look something like this:

Solution Screenshot

  1. Open IntegrationPhone/Exercises/index.html in a file editor.
  2. Add a button to the home page with id findweather and label "Local Weather".
  3. Note that a new page (#weather) has been added for you; it contains a listview with id weatherconditions.
  4. Using the demo above as an example, write code to call the Geolocation API getCurrentPosition function when the user clicks the button.
  5. On successful retrieval of the user's location, use the $.getJSON function to retrieve weather data; the URL supplied should be of the format ws.geonames.org/findNearByWeatherJSON?lat=43.048122&lng=-76.147424 but, of course, with the user's latitude and longitude.)
  6. GeoNames will return an object with the weather data - use $.each to iterate over the fields and add each name/value pair to the weatherconditions listview.
  7. Change the page to #weather and refresh the #weatherconditions listview.
  8. Be sure to test your code in a mobile browser.

Solution:

IntegrationPhone/Solutions/index.html

Code Explanation:

We add a handler to listen for clicks on the #findweather button, calling navigator.geolocation.getCurrentPosition. A successful geolocation calls weatherObservation.search.

The search function requests JSON data from GeoNames, sending the user's latitude and longitude as part of the request URL. We iterate over the object returned to populate the #weatherconditionslistview with the results.

Video

The ease of embedding video from sites like YouTube or Vimeo is great - but embedding isn't always a perfect option. Worries over intellectual property rights (others can embed my videos), loss of traffic (visitors view my videos on YouTube instead of my site), professionalism (worries that visitors might think my site less professional if videos are embedded), and other concerns might dictate that you host your videos on your own site.

The HTML5 video tag, along with appropriate choices for video file format, makes relatively easy the process of presenting videos to be playable regardless of the viewing device.

First, let's look at the video tag:

<video width="480" height="270" controls poster="images/poster.png">
<source type="video/mp4" src="videofile.mp4"></source>
<source type="video/webm" src="videofile.webm"></source>
<source type="video/ogg" src="videofile.ogv"></source>
<p>Your browser does not support the video tag</p>
</video>

Code Explanation:

The width and height attributes set the width and height, of course; we'll also set the CSS max-width of the video element to ensure a responsive handling of width. The presence of the controls attribute dictates that the player will show controls ("play", "pause", etc.) The poster attribute is the image to show on the player before video playing starts.

The video tag encloses a series of source tags, which specify alternative video files from which the browser may choose, depending on the media types or codecs the browser supports.

In the example above, we offer browsers three options to pick from: .mp4, .webm, and .ogg versions of our video.

Last, the content inside the video tag but outside the source tags is what users will see if their browser does not support the video tag.

Video Formats

Specifics about video file formats is a bit beyond the scope of this course. What we really need is a list of best formats to use and some information on how to convert to those formats.

Flash video, often the format in which embedded video is presented for desktop browsers, generally won't work on mobile devices. Instead, we'll concentrate on three formats:

Video File Formats
Format File Extension Notes
MPEG 4 .mp4 Based on Apple older QuickTime format; supported natively in all browsers.
Ogg .ogv, .ogg Open source; unencumbered by patents; supported natively by Firefox >3.5, Opera >10.50, Chrome >3.0.
WebM .webm New (2010) format; supported natively by Chrome, Firefox, and Opera.

So to publish video - specifically, video able to be viewed on different desktop and smartphone browsers - we do the following:

  1. Take our original video file (the raw file from the camera).
  2. Convert it to each of the file formats above.
  3. Publish with the video tag.

The user sees a video player with their browser - whether it be Safari on an iPhone, Internet Explorer on a Windows PC desktop, or anything else - picking the video format that works best.

Further Reading

Dive Into HTML5 is a great resource for more information on HTML5 in general; Video on the Web is, in particular, an excellent source of information on creating, saving, and publishing video in HTML5 and, thus, for mobile viewing.