25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Download from Wow! eBook <br />

112<br />

CHAPTER 4 ■ USING THE <strong>HTML</strong>5 GEOLOCATION API<br />

Let’s break that example down a little. As before, we’ve got a function to update our status value on<br />

the page, as shown in the following example.<br />

function updateStatus(message) {<br />

document.getElementById("status").inner<strong>HTML</strong> = message;<br />

}<br />

Our status here will be a simple text display, although this approach applies equally well for more<br />

compelling graphical status displays (see Listing 4-16).<br />

Listing 4-16. Showing the status<br />

navigator.geolocation.getCurrentPosition(updateLocation,<br />

handleLocationError,<br />

{timeout:10000});<br />

// 10 second timeout value<br />

updateStatus(“Requesting location data…”);<br />

Once again, we use the Geolocation API to get the user’s current position, but with a set timeout of<br />

ten seconds. Once ten seconds have elapsed, we should either have a success or failure due to the<br />

timeout option.<br />

We immediately update the status text display to indicate that a position request is in progress.<br />

Then, once the request completes or ten seconds elapses—whichever comes first—you use the callback<br />

method to reset the status text, as shown in Listing 4-17.<br />

Listing 4-17. Resetting the status text<br />

function endRequest() {<br />

updateStatus("Done.");<br />

}<br />

function updateLocation(position) {<br />

endRequest();<br />

// handle the position data<br />

}<br />

A simple extra, but easy to extend.<br />

This technique works well for one-shot position lookups because it is easy for the developer to<br />

determine when a position lookup request starts. The request starts as soon as the developer calls<br />

getCurrentPosition(), of course. However, in the case of a repeated position lookup via<br />

watchPosition(), the developer is not in control of when each individual position request begins.<br />

Furthermore, the timeout does not begin until the user grants permission for the geolocation service<br />

to access position data. For this reason, it is impractical to implement a precise status display because<br />

the page is not informed during the instant when the user grants permission.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!