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);
});
@paulirish
Copy link
Author

Basically it protects against some problems you'll get if you concatenate another method/file up against this one..

like

(function(){ ........ })()

(function(){  ..otherthing.... })();

will throw errors you dont like.

@mars
Copy link

mars commented Jan 13, 2012

@landua, This runs on the client so any Google API rate limiting would be per-user not across your entire user-base.

@landau
Copy link

landau commented Jan 19, 2012

I know that. I mean, what is the number of times my domain can load said script.

@paulirish
Copy link
Author

It is unclear what the story there is.
http://code.google.com/apis/loader/

@landau
Copy link

landau commented Jan 20, 2012

Darn. :( Thanks!

@tantalor
Copy link

@macek The semicolon helps terminate any lines before this script when concatenated with another file.

See also http://www.johntantalo.com/blog/dangers-of-anonymous-function-closures/

@Integralist
Copy link

@paulirish I'm building a map application and have noticed that although IE9 supports the geolocation api it incorrectly calculates the latitude/longitude.

Other users have also noticed this http://social.technet.microsoft.com/Forums/en-IE/ieitprocurrentver/thread/aea4db4e-0720-44fe-a9b8-09917e345080, but no amount of googling brings up any results from developer blogs/more technical readers... which I find just bizarre?

Do you (or anyone else for that matter) have any idea why this would be because it makes feature detecting the geolocation api damn near impossible. Also, I noticed that the fallback (as provided in the above polyfill) also has the same issues as found in IE9's native implementation?

@Integralist
Copy link

@paulirish actually, ignore my above comment. I investigated further how geolocation actually works (e.g. gets location of ip address, then triangulates user location based on nearby wifi hotspots) and realised that the fallbacks can only then work by getting the location of the ip address and the application I'm working on depends on the user location being accurate. So in my instance I can only really support genuine geolocation/GPS capable devices. Annoying still though that IE9's implementation is not accurate compared to other devices as it means an IE9 user may end up using the app even though it wont work correctly for them (e.g. browser sniff time? FUGLY)

@vancefsmith
Copy link

Hi, I am getting an error on line 21/22.

Error: error: 'google.loader.ClientLocation.latitude' is null or not an object

Im running the following on page load:

function initialize() {
Modernizr.load({
test: Modernizr.geolocation,
nope: 'js/geolocation.js',
complete: initializeMap()
});
}

and have the following scripts attached to my page:

modernizr.custom.65531.js
//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
//maps.google.com/maps/api/js?sensor=true

Any insights as to what the problem may be?

@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