Skip to content

Instantly share code, notes, and snippets.

@paulirish
Created April 14, 2010 18:59
Show Gist options
  • Save paulirish/366184 to your computer and use it in GitHub Desktop.
Save paulirish/366184 to your computer and use it in GitHub Desktop.
html5 geolocation with fallback.
// geo-location shim
// currentely only serves lat/long
// depends on jQuery
// doublecheck the ClientLocation results because it may returning null results
;(function(geolocation){
if (geolocation) return;
var cache;
geolocation = window.navigator.geolocation = {};
geolocation.getCurrentPosition = function(callback){
if (cache) callback(cache);
$.getScript('//www.google.com/jsapi',function(){
// sometimes ClientLocation comes back null
if (google.loader.ClientLocation) {
cache = {
coords : {
"latitude": google.loader.ClientLocation.latitude,
"longitude": google.loader.ClientLocation.longitude
}
};
}
callback(cache);
});
};
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);
});
@chrisnicola
Copy link

@vancefsmith internet connection problem would be my best guess. The shim downloads a script from google to access the 'google' javascript API objects.

@jeffreybarke
Copy link

@vancefsmith and @LucisFerre I would not recommend using this polyfill. As far as I can tell, google.loader.ClientLocation is no longer supported and always returns null. See http://grokbase.com/t/gg/google-ajax-search-api/126whx58ap/google-loader-api-not-working or Google "google.loader.ClientLocation is always null."

At minimum, I would wrap 19-24 in a conditional:

if (google.loader.ClientLocation) {
    cache = {
        coords: {
            "latitude": google.loader.ClientLocation.latitude,
            "longitude": google.loader.ClientLocation.longitude
        }
    };
}

@paulirish
Copy link
Author

added your conditional, jeffrey and made mention about the null values at the top.

I mostly agree with you that this polyfill is of questionable value these days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment