HTML5 Guidelines for Web Developers

(coco) #1

200 Chapter 7—Geolocation


As soon as the page is fully loaded, the current location is determined and exist-
ing entries are displayed:

window.onload = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(pos) {
my_pos = pos;
showItems();
},
posError,
{ enableHighAccuracy: true, maximumAge: 60000 }
);
}
showItems();
if (localStorage.length > 0) {
drawAllItems();
}
}

The option enableHighAccuracy is activated to call getCurrentPosition(). The
maximum time for reusing an already determined position is one minute. If the
position is successfully determined, the previously defined global variable my_pos
is assigned the values of the just determined position and then the function show-
Items() is called. An error in determining the position leads to calling the func-
tion posError(), a function that outputs the corresponding error message in a
dialog window. If the number of elements in the localStorage is greater than 0 ,
the function drawAllItems() is executed as well, displaying existing entries on
Google Maps.
The showItems function assembles a string of all entries and assigns it to the
HTML element with the ID items:

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