Skip to content

Instantly share code, notes, and snippets.

@psayre23
Forked from paulirish/gist:366184
Created August 12, 2012 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psayre23/3330084 to your computer and use it in GitHub Desktop.
Save psayre23/3330084 to your computer and use it in GitHub Desktop.
html5 geolocation with fallback.
// geo-location shim
// currentely only serves lat/long
// doublecheck the ClientLocation results because it may returning null results
(function (geolocation) {
if (geolocation) return;
var cache;
var head;
geolocation = window.navigator.geolocation = {};
geolocation.getCurrentPosition = function (callback) {
if (cache) callback(cache);
head = head || document.head || document.getElementsByTagName('head')[0] || document.documentElement;
var script = document.createElement('script');
script.async = 'async';
script.src = '//www.google.com/jsapi';
script.onload = script.onreadystatechange = function (_, isAbort) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
script = void undefined;
if ( !isAbort ) {
// sometimes ClientLocation comes back null
if (google.loader.ClientLocation) {
cache = {
coords : {
"latitude": google.loader.ClientLocation.latitude,
"longitude": google.loader.ClientLocation.longitude
}
};
}
callback(cache);
}
}
};
head.insertBefore( script, head.firstChild );
};
geolocation.watchPosition = geolocation.getCurrentPosition;
})(navigator.geolocation);
// usage
navigator.geolocation.watchPosition(function(pos){
console.log("I'm located at ",pos.coords.latitude,' and ',pos.coords.longitude);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment