Skip to content

Instantly share code, notes, and snippets.

@romannurik
Created October 2, 2009 02:24
Show Gist options
  • Save romannurik/199409 to your computer and use it in GitHub Desktop.
Save romannurik/199409 to your computer and use it in GitHub Desktop.
// http://earth-api-samples.googlecode.com/svn/trunk/demos/geolocation/location.js
/**
* Watches the user's current location, continually calling the successCallback
* with a Gears Coords-like object (latitude, longitude, accuracy) or
* errorCallback with an error object. The second argument to successCallback
* will be the location provider, i.e. 'gears', 'html5', or 'ip'.
*/
function watchLocation(successCallback, errorCallback, ipFallback) {
successCallback = successCallback || function(){};
errorCallback = errorCallback || function(){};
if (typeof ipFallback == 'undefined')
ipFallback = true;
// Set up IP-based fallback
var tryIPLocation = function(passthruError) {
var error = passthruError || new Error('Location could not be determined.');
if (ipFallback) {
// Try IP-based geolocation.
if (google.loader.ClientLocation) {
successCallback({
latitude: google.loader.ClientLocation.latitude,
longitude: google.loader.ClientLocation.longitude,
accuracy: -1
}, 'ip');
} else {
errorCallback(error);
}
} else {
errorCallback(error);
}
};
var locationProvider = 'html5';
// Try HTML5-spec geolocation.
var geolocation = navigator.geolocation;
// Try Gears geolocation.
if (!geolocation && window.google && google.gears) {
geolocation = google.gears.factory.create('beta.geolocation');
locationProvider = 'gears';
}
if (geolocation) {
// We have a real geolocation service.
try {
function handleSuccess(position) {
successCallback(position.coords, locationProvider);
}
geolocation.watchPosition(handleSuccess, errorCallback, {
enableHighAccuracy: true,
maximumAge: 5000 // 5 sec.
});
} catch (err) {
tryIPLocation(err); // Pass-through error.
}
} else {
tryIPLocation();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment