Information Technology Reference
In-Depth Information
What Could Possibly Go Wrong?
Imagine you write your great check-in application, to take on the likes of Foursquare and
company. Your users are happy, and all is good with the world. Nothing could possibly
go wrong, right? Well, perhaps we spoke to soon.
On any device, at any time, you can find yourself having to deal with a range of issues
that prevent your geolocation code from returning an accurate value, or even any value
at all. It could be the weather, the alignment of the sun and the planets (actually, that's
less of a joke than you might think), or even user intervention. Whatever the cause, there
are well-defined error states that you should handle in your code.
The four main error conditions that can exhibit under the HTML5 specification are:
TIMEOUT : No location mechanism responded within the allowed time
with location data.
POSITION_UNAVAILABLE : Your device has one or more valid
location mechanisms (such as GPSor WiFi), but none of them could
provide valid location data.
PERMISSION_DENIED : The browser was prevented from accessing
the HTML5 geolocation API by reason of permissions. Either the user
blocked access when prompted, or the browser is configured explicitly
to block access.
UNKNOWN_ERROR : For reasons unknown, location data was not
available.
It's all well and good to know what the error conditions are, but how does one make use
of them? You'll remember we said the getCurrentPosition() function had a myriad of
overloaded versions. A significant subset of these include a common pattern of
accepting a callback function for reporting position as the first parameter, and a callback
function for error handling as the second parameter. Take a look at the next iteration of
our sample application, in the file ch09-example03.html. The key change is to our
checkIn() JavaScript function, which now looks like this.
function checkIn () {
var geoData = "";
if (supportsGeo()) {
navigator.geolocation.getCurrentPosition(
function(position) {
geoData = position.coords.latitude + ", " + position.coords.longitude;
},
function(error) {
switch(error.code) {
case error.TIMEOUT:
alert ('Geolocation returned a timeout error');
break;
case error.POSITION_UNAVAILABLE:
alert ('Geolocation returned a position unavailable error');
break;
 
Search WWH ::




Custom Search