Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Geolocation lookup that accepts an error-first callback

Geolocation lookup

Retrieve geolocation of user in under 140 bytes.

The function takes in a callback which will return:

/**
 * @callback {Mixed} arguments[0] Error if there is one (either browser specific or 1 if geolocation is not available)
 * @callback {Object} arguments[1] Coordinates of the user
 * @callback {Number} arguments[1].latitude Latitude of the user; ranges from -180 (180S) to 180 (180N)
 * @callback {Number} arguments[1].longitude Longitude of the user; ranges from -180 (180W) to 180 (180E)
 */
// Original available: https://gist.github.com/4053059
// Asynchronous retrieval of coordinates
function getCoordinates(cb) {
// Grab geolocation from the navigator
var geolocation = window.navigator.geolocation;
// If geolocation exists, start fetching location
if (geolocation) {
geolocation.getCurrentPosition(function (position) {
cb(null, position.coords);
}, cb);
} else {
// Otherwise, callback with an error
cb(1);
}
}
function(c,g){g=navigator.geolocation;g?g.getCurrentPosition(function(p){c(null,p.coords)}):c(1)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE http://twolfson.com/
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "geolocationLookup",
"description": "Geolocation lookup that accepts an error-first callback",
"keywords": [
"geolocation",
"browser",
"error-first"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>Lat: ##.####, Lng: ##.####</b></div>
<div>Actual value: <b id="ret"></b></div>
<em>Be sure to accept the geolocation request.</em>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function(c,g){g=navigator.geolocation;g?g.getCurrentPosition(function(p){c(null,p.coords)}):c(1)}
var $ret = document.getElementById( "ret" );
// Grab the output and the geolocation
myFunction(function (err, coords) {
// If there was an error, update the text accordingly
if (err) {
$ret.innerHTML = 'Geolocation could not be used =(';
} else {
// Otherwise, output the coordinates
$ret.innerHTML = 'Geolocation found!! Lat: ' + coords.latitude + ' Lng: ' + coords.longitude;
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment