542 CHAPTER 14 Making your HTML location-aware
$(document).ready(function () {
getLocation();
});
function supportsGeolocation() {
return 'geolocation' in navigator;
}
function showMessage(message) {
$('#message').html(message);
}
function getLocation() {
if (supportsGeolocation()) {
navigator.geolocation.getCurrentPosition(showPosition);
}
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);
}
The document ready function calls the getLocation function. In the getLocation function
an if statement determines whether it should attempt to call the getCurrentPosition method
by calling the supportsGeolocation function. The supportsGeolocation function checks
whether the navigator global variable has a geolocation property.
When the getCurrentPosition method is called, the showPosition function is passed. The
showPosition function is called when the position information has been successfully obtained.
When the showPosition function is called, it’s passed a Position object that contains a coords
and timestamp property. Figure 14-1 shows the rendered result.
FIGURE 14-1 he rendered current position and converted timestampT