190 Chapter 7—Geolocation
7.2 A First Experiment: Geolocation in the Browser
To test your browser’s geolocation function, you just need the JavaScript code in
Listing 7.3:
Listing 7.3 Function for outputting position with “navigator.geolocation”
function $(id) { return document.getElementById(id); }
window.onload = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(pos) {
$("lat").innerHTML = pos.coords.latitude;
$("lon").innerHTML = pos.coords.longitude;
$("alt").innerHTML = pos.coords.altitude;
},
function() {},
{enableHighAccuracy:true, maximumAge:600000}
);
} else {
$("status").innerHTML =
'No Geolocation support for your Browser';
}
}
The first line of the listing defines an auxiliary function $ , allowing for an abbre-
viated notation of the function document.getElementById() (similar to an alias).
This trick was taken from the familiar jQuery library and is very convenient for
our example, because the elements that need to be filled are marked with an ID
attribute on the website. As in the previous examples (see Listings 7.1 and 7.2),
window.onload ensures that the content of the website is fully loaded before refer-
ences to HTML elements are set. The first if query checks if the browser supports
the Geolocation API. If that is not the case, an appropriate message is written into
the element with the ID status. Otherwise, the actual function for determining
position is activated: navigator.geolocation.getCurrentPosition().
According to the specification, the browser has to ask when calling this function
if you want it to locate your current position and share it on the website. Fig-
ure 7.1 shows the relevant dialog box in Mozilla Firefox.