-
-
Save psayre23/3330084 to your computer and use it in GitHub Desktop.
html5 geolocation with fallback.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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