My Pages

Wednesday 22 June 2011

Mobile Web Development - Geolocation

Introduction


Mobiles have become ubiquitous in today’s modern life style. Mobiles started out as a portable telephone used to make mobile telephone calls across a geographic area . Technological advances in both mobile technology and mobile web standards brought the Internet in the palm of our hands. There are limitations when one compares Internet browsing from a PC or a laptop to a mobile such as navigation and speed.

With the introduction to HTML5 mobile web development is taking a different shape. A survey conducted by Web Directions found that 2010 saw an explosion of interest and activity by developers in HTML5, and developing native apps for mobile platforms like iOS and Android using web technologies.

This blog entry will focus on developing a mobile web application using geolocation. Geolocation is the technical term used in figuring out where you are on the map and maybe share you location if need be.  Finding your location can be achieved in numerous ways such as;

  • IP address
  • Wireless network connection
  • Cell tower connected to the phone
  • GPS hardware receiving latitude and longitude information from satellites


Privacy is a concern when talking about geolocation in fact the geolocation API which we will be discussing states that location information shouldn’t be sent to web sites without the confirmation of the user.

The geolocation API is an interface by which latitude and longitude information are available through Javascript. This information can be sent to a remote server or used to pin point your location on a map. This API is supported in most modern browsers on both desktop and mobile devices.


Task Summary


The tasks that will be demonstrated in this blog are;
  • Make use of the geolocation API to get location information
  • Display location on to google maps


W3C Geolocation API


The geolocation API offered by the W3C centers around a property of the DOM navigator object;
navigator.geolocation

The simplest use of the geolocation API looks like this;

Simplest use of the geolocation object in navigator

In the script shown above there is no error handling and no options. The web application should probably include at least the first two of those. When running this code for the first time the browser asks you one whether you want to reveal you location. This means that the browser will never force you to reveal you current physical location. User experience differs from browser to browser.

To recap when the getCurrentPosition(callbackfunc) is called the following takes place;
  • The user is asked if he/she wants to know his/her location
  • The website asking for the location
  • Can change security settings
  • Can choose to share or not share the location
  • Can choose to tell the browser to keep the choice and never ask again


The getCurrentPosition function takes a call back function which in the example shown above is show_map. The call will return immediately but doesn’t mean that you have access to the location. The location information will be available in the call back function.

passing callback function in getCurrentPosition()

The callback function will be called with a single parameter, an object with two properties coords and timestamp. The timestamp is just that, the date and time when the location was calculated. The coords object has properties like latitude and longitude that represent exactly what they sound like which is the user’s physical location. The position object’s properties are ;


PropertyDescription
coords.latitudeA double in decimal degrees
coords.longitudeA double in decimal degrees
coords.altitude A double or nulle in meters
coords.accuracyA double in meters
coords.altitudeAccuracyA double or null in meters
coords.headingA double or null in degrees clockwise
coords.speedA double or null in m/s
timestampA DOM timestamp like the Date() object


With the exception of latitude, longitude, altitude and accuracy the result from the properties might be null.

In both examples shown above no error handling is performed except when checking that the geolocation is defined. The function getCurrentPosition() takes a second argument which is an error handling callback function.
Handling errors using error callback function

In the function shown above the positionError object will contain a number if an error has occured. The number represents an error type a shown in the image above.

The remaining sections a demonstration of geolocation on Opera mobile emulator will take place. The version used in this demonstration is V11 and can be downloaded for free from download.
Page to demonstrate geolocation

To demonstrate the geolocation API I created an HTML document which at this point will host three functions;
  • Call geolocation API
  • Handle results from getCurrentPosition()
  • Handle any errors from getCurrentPosition()


Geolocation function with display and error handler functions

The function above first checks that the geolocation object in the DOM navigator is defined. Then if the getCurrentPosition() function yielded any results the display_loc(position)  function is called.

display_loc() function

This function takes the position object and displays the results in table cells by accessing the innerHTML property.  The last function created handles any errors which could result from the getCurrentPosition() function. The code used has already been shown in a previous snippet.

The following result is achieved;

Displaying location information

An interval was created so as to refresh the location information every 60 seconds. A Stop Tracking button was also added so as to stop the timer from re-executing the script.



Google Maps


I found this part of the demonstration quite interesting. At this point in our script we have all the information we need to pin point our location on a map (latitude and longitude). These two values can be passed as parameters into google static maps to show our locations. All the information I required was available at Google Static Maps API

To add the google maps feature all I had to do was to add an anchor tag which when the page loads is empty. When the geolocation function is triggered the anchor ‘s href attribute is filled with the following URL containing my latitude and longitude positions.

URL called when clicking on link.

The display_maplink(latitude,longitude) function is called from the callback function of the getCurrentPosition() function. If an error has occured while getting the positioning information the anchor tag is set to hidden from the page.

Displaying Show Map anchor
Displaying static google map using geolocation position



Conclusion


At this point we have covered the W3C geolocation API but that is not all there is on geolocation. It is well known that  there is an Open source browser plug-in from Google called Gears that provides geolocation information. The advantage of this API is that it is supported by older browsers as well as new.
This has been an informative experience from which I have learned a lot on geolocation. The drawback of such an API as I see it is different browsers. Different browsers give different experiences to the user which one might not anticipate when designing geolocation web applications for mobiles. With the slow introduction to HTML5 one can only hope that one day web technologies and markup will be standardised and make our lives a little easier.


Wednesday 15 June 2011

Introduction to HTML 5


Introduction

HTML 5 is the latest in markup technology. Like it’s predecessors HTML 4.01, XHTML 1.0 and XHTML1.1 HTML5 provides new features that facilitate development for modern web applications. HTML5 also standardises features that web developers have been using throughout these last few years but never properly documented or integrated into one markup. HTML 5 is cross-platform which means that any operating system can take advantage of the new features of HTML5. The only technology required to run HTML5 is a web browser capable of parsing said markup. Most modern web browsers such as Chrome, Firefox and Internet Explorer support many of the HTML 5 features. Mobile web browsers that are installed on iPhones, iPads and Android phone all have support for HTML5.

Throughout this blog entry we will go through some of the new features which have been introduced with HTML 5 such as :

  • New markup elements such as <header>, <footer> and <section>.
  • The Canvas, which is an object that allows javascript programming.
  • Embedding of video into web page without resorting to a third party plug-in.
  • Geolocation which the user to share physical locations within a web application.
  • Persistent local storage without using third party plugins
  • Offline web applications.
  • Improvements to HTML web forms
  • Microdata that lets you create your own vocabularies beyond HTML 5.


HTML 5 is designed to be backward compatible with each version of a browser. Using HTML 5 one can also check whether a particular feature is available in a given browser version by using Javascript. HTML 5 is a cooperation between the W3C ad the Web Hypertext application technology Working Group. These are some of the rule that were established for HTML 5;

  • New features are based on HTML, CSS, DOM and Javascript
  • Reduce the need for third party plugins such as Flash
  • Improve error handling
  • Markup that replaces scripting
  • Device independent
  • The development process should be visible to the public


One major factor in HTML 5 which wasn’t given the required attention in previous versions is MIME Types. MIME Types declare the type of content that the browser or server is parsing. We will see in later demonstration the use and importance of MIME types.
Task Summary

I found HTML 5 quite an interesting topic to read. This is a breakdown of the tasks that will be demonstrated in the remaining sections of this blog entry;

  • New and changed markup in HTML5
  • Demonstrate the canvas element
  • Demonstrate Media Elements
  • Demonstrate new form elements



New and changed markup in HTML5

The bare minimum markup that is required to create an HTML 5 web page is very similar to XHTML 1.1 with some very small changes.

Basic web page in HTML 5

From the markup shown above notice that the DOC Type declaration has become more concise and only required as a backward compatibility feature to older browsers. The MIME type is defined in the <head> section were it states that the content within the HTML document is of content type text/html.

HTML5 defines a number of new semantic elements. The following are some of the new elements which are defined by the HTML5 specification;


ElementDescription
<section>This element represents a generic section of a document or application. A section, in this context is a group of content, typically with a heading. For example a home page could be split into different sections example about us, what’s new etc.
<nav>This element represents a section of a page that links to other pages or parts of the same page.
<article>A self contained composition in a document that is intended to be reused such as syndication
<aside>Represent content that is related to the content touching the element.
<hgroup>Represents the heading of a section. It can be used to group a set of h1 - h6 elements to represent sub headings.
<header>Represents a group of headings or navigations. Can be used to include <hgroup> or a set of h1 - h6 elements. This element can also be used to wrap a section’s table of contents or a search form
<footer>This elements represents a footer for the parent element sectioning element.
<time>Represents time on a 24 hour clock or a date from the Gregorian calendar.
<mark>Highlights specific text in a given content element
<figure>Contains pictorial content relevant to the content nested in. This element usually contains images, diagrams, code etc.



Demonstrating Headers

The main purpose for creating a header element apart from the obvious is to give meaning to the document markup. This means that a header element defines a document outline of a document as opposed to using a div tag. Header elements like <h1> and <h2> give page structure. Taken together, they create an outline that you can use to visualize a page. Screen readers use document outlines to provide navigation in a page. In previous version of HTML elements h1 to h6 were the only way to create a document outline.

Defining document outlines using header ,hgroup and h1 - 6 elements


Demonstrating Articles

In previous version of HTML to properly define a document outline only one h1-6 element could be defined. Articles create separate document outlines were in you can define an h1-6 element per article. The article element defines a self contained node in the document outlet, the h1 element provides the title for that outline node.

Allowing for multiple use of an h1 element without disrupting the document outline

Demonstrating Dates and Times

HTML 5 provides the <time> element to represent date and time. There are three parts to a <time> element;

  • A machine readable timestamp
  • Human-readable text content.
  • An optional pubdate flag.


The markup used in the demonstration specifies a date but not time. The format is a four-digit year, two digit month and two digit day separated by dashes.

Demonstrating the use of the element time

Demonstrating Navigation

Usually when on designed a navigation bar the <ul> and <li> element were used and then group the element in a styled div. Although this type of markup is still valid the introduction of the <nav> element  provides semantic meaning to the markup.

Using the <nav> element to wrap an unordered list for navigation


Canvas Element

The canvas element can be thought of as a drawing surface which can be used to render graphics such as graphs and games. A canvas when parsed is interpreted as a rectangle on the page which can use Javascript to draw lot of cool graphics. The markup of a canvas looks something like this;



Declaring a canvas element


When this markup is parsed through a browser the page is blank. To draw something on the canvas one must make use of Javascript like the example shown below;



Drawing a rectangle using Javascript


When the function draw_b() is called the canvas is assigned to a variable called b_canvas and then a 2D context is assigned to the variable b_context. Then a context function called fillRect(x,y,width,height) is called to draw the rectangle depicted below.



Rectangle drawn on canvas


From the script shown above one can notice that we get a 2D context to draw the required shape. The drawing context is where all the drawing methods and properties are defined. Some of the methods are  fillStyle, fillRect(x,y,width,height), strokeRect(x,y,width,height) and ClearRect(x,y,width,height).

Media Elements

Current HTML versions funnel multi-media content through proprietary plugins such as Real Player or Quicktime. HTML5 defines a standard way to embed video using the <video> element. This elements is not fully supported by all browsers and is still evolving. There are no restrictions on the video codec, audio codec or container format you can use for your video. The <video> element can be used in two ways. If only one video file is required one can simply link the video using the src attribute.



Using <video> element to load one video


In the <video> element declaration above the controls attribute sets a default set of controls to manage video playback. Other optional attributes are preload which downloads the video before playing it and playback which tells the browser to start playing the video as soon as possible.



A video playback of an .ogv video


When multiple videos codes must be available the <source> element is then introduced. The <source> element takes two attributes which are the src and the type. The type attribute specifies the video container such as video/ogg and the codecs which decode the video stream such as theora.



This markup allows for other videos of different type and codecs to be introduced




Form Elements

HTML 5 introduced about a dozen new input types that can be used in a form. In this section of this blog entry a demonstration of the different input types will be shown along with new attributes introduced in HTML5.



Placeholder Text



Placeholder text is displayed inside the input field as long as the field is empty and not focused.



Placeholder attribute


The following result is achieved;



Demonstrating placeholder text

Autofocus Fields



The current trend to focus a field is to use Javascript. Dealing with autofocus using Javascript has its disadvantages in some situations such as when pressing space bar and expecting the page to scroll. The autofocus field eliminates this problem.





autofocus attribute
The following result is achieved;



Demonstrating autofocus


Email Addresses and URL Fields



HTML5 defined several new input types and two of these types are email and url. Browsers that do not support these types of input will automatically disregard the attribute and treat the type as text.


Using email and url attributes


The following demonstration was performed on Opera Mobile Browser simulator.



Demonstrating HTML 5 input type attributes email and url on Opera Mobile browser


Numeric Text fields



Taking numeric values as input is trickier than accepting an email or a URL since when asking for numbers you are usually asking for a number within a certain range. HTML 5 provides numerous ways (pun intended) to accept numbers.



Spinbox Number: type=”number”
Slider Number: type=”range”



HTML markup to accept input using different types


This shows the different input controls displayed when using different input types with number.



Numeric text fields


Pickers



A pickers refers to a fields which when selected opens up a panel offering the user a choice from a group of items. Two of the most prominent pickers which are ubiquitous on the web are the date and color pickers. HTML 5 has provided two input types which provide said functionality. These input types are not yet fully supported by all browsers. This demonstration will take place on Opera Mobile Browser.



HTML markup to create date and color pickers

Demonstrating date picker on Mini Opera Browser



Search Boxes



The new search boxes available in HTML5 works differently on different browsers. When I tried to view the input field in chrome the field displayed itself as a normal text field but when I tried the same page on the Opera Mobile browser a search icon showed up. There is still lack of support for this input type amongst browsers.



Using the input type search text field

Demonstrating input type search


Conclusion

Working with HTML5 has been an exhilarating experience. Having done a lot of work using HTML5 ‘s predecessors I know how difficult it is to maintain the integrity of a page between browsers especially when using Javascript. I believe that there is still a lot of work to be done with regards to standardization and support of emerging elements between browsers. Time will come when HTML 5 will replace most of the third party plugins and software that nowadays encumber the web.