Location-based services are handy in all sorts of ways, from helping users with mobile devices find their way around to providing tailored information about the region they live in. The Geolocation API accesses a device’s location services, which use GPS, wireless, or cell tower data to provide information about the device’s location that will be used by your location-based apps.
Location data obviously involves privacy concerns, so in most (if not all) browsers, users must give explicit permission to access this data, usually in the form of an on-screen prompt that allows them to opt in or out of providing their location, as shown in Figure 6-1.
The data is held in the geolocation object, a child of window.navigator, which you can access using the getCurrentPosition() method:
navigator.geolocation.getCurrentPosition(function(where){
// Do something
});
A successful callback returns an object (I’ve called it where) containing a coords child object. This child object has a series of properties pertaining to the user’s position, such as his or her altitude and heading, but the ones I’m really interested in are latitude and longitude. In this code, I’m accessing these properties and displaying them in an alert:
navigator.geolocation.getCurrentPosition(function(where){
alert(where.coords.latitude + ',' + where.coords.longitude);
});
You can try this for yourself in position-current.html; my results are shown in Figure 6-2.
geolocation object, referencing the street I live on; please don’t stalk me.
Occasionally an error is returned when looking for the position; an optional error callback can check for this. The following code creates two functions, one for successful location and one for an error:
var geo = navigator.geolocation,
lcn_success = function(where) { … },
lcn_error = function() { … };
geo.getCurrentPosition(lcn_success, lcn_error);
Sometimes a GPS device can take a little while to find the user’s exact position, and, of course, the user may also be on the move, so instead of a one-off location, you can choose to watch the user’s position, receiving updated results when location data changes. You do this with the watchPosition() method, also on the geolocation object, which works in the same way as getCurrentPosition():
navigator.geolocation.watchPosition(function(where){
console.log(where.coords.latitude,where.coords.longitude);
});
To cancel watching a user’s position, use the clearWatch() method with the unique ID created by the watchPosition() method; in this example, the process ends when the user clicks the #stop link:
var geo = navigator.geolocation,
watchID = geo.watchPosition( … ),
endWatch = document.getElementById('stop');
endWatch.addEventListener('click', function () {
geo.clearWatch(watchID);
}, false);
In position-watch-clear.html, you can see a demo of this in action. Open the page in a mobile device and move around, and you should see the location update as your device gets a better fix on your location.