User location
Monitor the user's location
The Geolocation API lets you watch where the user is and keep tabs on them as they move around, always with the user's consent.
The Geolocation API lets you watch where the user is and keep tabs on them as they move around, always with the user's consent.
The API is device-agnostic; it doesn’t care how the browser determines location, so long as clients can request and receive location data in a standard way. The underlying mechanism might be via GPS, wifi. Since any of these lookups is going to take some time, the API is asynchronous; you pass it a callback method whenever you request a location.
TL;DR
The Geolocation API allows you to obtain the user’s location (with user consent) with a single call to
getCurrentPosition()
.
If you want to continually monitor the location of the user, the geolocation API has a method called
watchPosition()
. It operates in a similar way to
getCurrentPosition()
yet it will fire multiple times as the positioning software:
var watchId = navigator.geolocation.watchPosition(function(position) {
document.getElementById('currentLat').innerHTML = position.coords.latitude;
document.getElementById('currentLon').innerHTML = position.coords.longitude;
});
Watching for changes to a geolocation is not a free operation. Whilst operating systems might be introducing platform features to let applications hook in to the geo subsystem, you as a web developer have no idea what support the user’s device has for monitoring the user’s location and whilst you are watching a position you are engaging the device in a lot of extra processing
Once you have no need to track the user’s position call
clearWatch
to turn of the geolocation systems.
Unfortunately, not all location lookups are successful. Perhaps a GPS could not be located or the user has suddenly disabled location lookups. A second, optional, argument to getCurrentPosition() will be called in the event of an error, so you can notify the user inside the callback:
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
};
var geoError = function(position) {
console.log('Error occurred. Error code: ' + error.code);
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable (error response from location provider)
// 3: timed out
};
navigator.geolocation.watchPosition(geoSuccess, geoError);
};
Updated on 2014-01-06
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License , and code samples are licensed under the Apache 2.0 License . For details, see our Site Policies .