Lesson 1: Basic positioning CHAPTER 14 543
Handling errors
You must handle errors when calling methods on the Geolocation object. You handle errors
by adding another callback parameter to the call so that the first parameter is the success
callback, and the second parameter is the error callback.
The following code demonstrates the use of the error callback when calling the
getCurrentPosition method.
/// <reference path="jquery-1.8.3.js" />
$(document).ready(function () {
getLocation();
});
function supportsGeolocation() {
return 'geolocation' in navigator;
}
function showMessage(message) {
$('#message').html(message);
}
function getLocation() {
if (supportsGeolocation()) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else {
showMessage("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var datetime = new Date(position.timestamp).toLocaleString();
showMessage("Latitude: " + position.coords.latitude + "<br />"
+ "Longitude: " + position.coords.longitude + "<br />"
+ "Timestamp: " + datetime);
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
showMessge("User denied Geolocation access request.");
break;
case error.POSITION_UNAVAILABLE:
showMessage("Location information unavailable.");
break;
case error.TIMEOUT:
showMessage("Get user location request timed out.");
break;
case error.UNKNOWN_ERROR:
showMessage("An unknown error occurred.");
break;
}
}