Hands on: Geolocation using HTML5

Learn how to use HTML5 to plot points on a map and determine current position

1 2 3 4 5 6 7 8 9 Page 9
Page 9 of 9

The showItems function assembles a string of all entries and assigns it to the HTML element with the ID items:

function showItems() { <br>   var s = '<h2>'+localStorage.length+' Items for ' <br>     +location.hostname+'</h2>'; <br>   s+= '<ul>'; <br>   var i_array = getAllItems(); <br>   for (k in i_array) { <br>     var item = i_array[k]; <br>     var iDate = new Date(item.ts); <br>     s+= '<li>'; <br>     s+= '<p class="msg">'+item.msg+'</p>'; <br>     s+= '<div class="footer">'; <br>     s+= '<p class="i_date">'+iDate.toLocaleString(); <br>       +'</p>'; <br>  . . .<br>   $('items').innerHTML = s+'</ul>';

The variable i_array is filled with the result of the function getAllItems(), which reads the localStorage, returns the contents as objects in an array, and sorts the objects by date:

function getAllItems() { <br>   var i_array = []; <br>   for (var i=0;i<localStorage.length;i++) {<br>     try { <br>       var item = JSON.parse( <br>         localStorage.getItem(localStorage.key(i)) <br>       ); <br>       i_array.push(item);<br>     } catch (err) { <br>       continue;   // skip this entry, no valid JSON data <br>     } <br>   } <br> <b>  i_array.sort(function(a, b) { <br>     return b.ts - a.ts <br>   }); </b><br>   return i_array; <br>  }

The call localStorage.getItem() gets an element from the persistent memory, converting it to a JavaScript object via the function JSON.parse. The requirement is that the object be converted to a string with JSON.stringify during saving (see the following code listing). To avoid the script being aborted due to any items in local storage that are not JSON encoded, the instruction is enclosed in a try/catch block. The objects are added to the end of the array i_array with i_array.push() and sorted by date in the next step. To tell the JavaScript function sort which criteria it should sort by, it is expanded with an anonymous function. The variable ts allows temporal sorting of the objects. It contains the numbers of milliseconds since 1.1.1970, a value created via the JavaScript function new Date().getTime(). If the anonymous function returns a negative value, a is arranged after b; for a positive value, a comes before b.

We still need to answer the question about how new entries are created and saved. The function saveItem() takes care of this, initializing a local variable d to which we assign the structure diaryItem:

function saveItem() { <br>   var d = diaryItem; <br>   d.msg = $('note').value; <br>   if (d.msg == '') { <br>     alert("Empty message"); <br>     return; <br>   } <br>   d.ts = new Date().getTime(); <br>   d.id = "geonotes_"+d.ts; <br>   if (navigator.geolocation) { <br>     $('status').innerHTML = '<span style="color:red">' <br>         +'getting current position / item unsaved</span>'; <br>     navigator.geolocation.getCurrentPosition( <br>       function(pos) { <br>         <b>d.pos = pos.coords; <br>         localStorage.setItem(d.id, JSON.stringify(d)); </b><br>         $('status').innerHTML = <br>           '<span style="color:green">item saved. Position' <br>           +' is: '+pos.coords.latitude <br>           +','+pos.coords.longitude+'</span>'; <br>         showItems(); <br>       }, <br>       posError, <br>       { enableHighAccuracy: true, maximumAge: 60000 } <br>     ); <br>   } else { <br>     // alert("Browser does not support Geolocation"); <br>     localStorage.setItem(d.id, JSON.stringify(d)); <br>     $('status').innerHTML = <br>       "Browser does not support Geolocation/item saved."; <br>   } <br>   showItems(); <br>  }

If the text field is empty (d.msg = ''), a corresponding dialog appears and the function is terminated with return. Otherwise, the timestamp is set to the current millisecond, and the entry's ID is assembled from the string geonotes_ and the timestamp. If several applications should access the localStorage from one server, the string prefix can help to distinguish the data. After the position has been successfully determined, the variable pos within the diaryItem object is filled with coordinates and the appropriate meta information, and then saved as a JSON string in the localStorage via JSON.stringify().

If the browser does not support the Geolocation API, the application saves the text anyway and points out that there is no support. The final call of showItems() ensures that the list of messages is updated.

Browser Support

As mentioned previously, the functions for determining location offer many new possibilities, especially for use on mobile devices. The most important mobile platforms at the time of this writing are products by Apple (iPhone, iPad, iPod) and Android cell phones. Both Google's browser (standard on the Android platform) and Safari (for Apple devices) support the Geolocation API.

Desktop browsers also offer a good level of support. Safari and Google Chrome include the required functions from version 5 and later; Firefox has been Geolocation-capable since version 3.5. Opera integrates the function in its browser in version 10.60 and later. Only Microsoft still fails to offer support for any kind of geolocation in the browser, and unfortunately, this even applies to the mobile platform Windows Phone 7.


With the rapid spread of smartphones, location-based services are becoming available to more and more people. They make it easy for users on the move to gather information, be it finding the nearest cash machine or the best public transport connection. At the moment, these tasks are still carried out by special apps that have to be developed and constantly updated separately for each mobile operating system. By implementing the Geolocation API, such functions can in the future be handled by the browser.

This article is excerpted from the book HTML5 Guidelines for Web Developers and is reprinted by permission of publisher Pearson/Addison-Wesley Professional. Copyright 2011 Pearson Education, Inc., all rights reserved.

Copyright © 2011 IDG Communications, Inc.

1 2 3 4 5 6 7 8 9 Page 9
Page 9 of 9
7 inconvenient truths about the hybrid work trend
Shop Tech Products at Amazon