public
Last active

html5 geolocation with fallback.

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
// 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);
});

This is still really basic btw. Wouldnt be hard to remove jQuery dependency and flesh out things... error handler for instance.

alexander farkas has done a nice expanded polyfill for geolocation
http://github.com/aFarkas/webshim/blob/master/src/shims/geolocation.js

@paulirish, regarding line 6, I have not seen the ; prefixing a function like that. What is the utility of this semicolon?

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.

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

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

Darn. :( Thanks!

@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/

@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?

@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)

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?

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

@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
        }
    };
}

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.