Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created July 28, 2009 02:22
Show Gist options
  • Save kara-ryli/156883 to your computer and use it in GitHub Desktop.
Save kara-ryli/156883 to your computer and use it in GitHub Desktop.
A primer for using the W3C geolocation API supported in Firefox 3.5 and MobileSafari
var Geo = navigator.geolocation, // {Object|null} a shortcut to the geolocation static class
options = { // {Object} options available to calls for position
enableHighAccuracy: false, // {Boolean} Whether or not to use more resources to get a more accurate position
maximumAge: 0, // {Number|Infinity} The maximum number of milliseconds since the last check.
timeout: null // {Number|null} The maximum number of milliseconds to wait for a fix
},
watchId; // {Number} an ID to a watch timeout
// handles an error finding the user's position
function onError(error) {
var message = error.message,
code = error.code;
switch(error.code) {
case error.UNKNOWN_ERROR:
break;
case error.PERMISSION_DENIED:
break;
case error.POSITION_UNAVAILABLE:
break;
case error.TIMEOUT:
break;
}
}
// handles position data once found
function onPosition (position) {
var timestamp = position.timestamp, // {Date}
coords = position.coords, // {Object} placeholder
latitude = coords.latitude, // {Number} decimal degrees
longitude = coords.longitude, // {Number} decimal degrees
accuracy = coords.accuracy, // {Number} meters
altitudeAccuracy = coords.altitudeAccuracy, // {Number|null} meters
heading = coords.heading, // {Number|null} degrees relative to true north
speed = coords.speed; // {Number|null} meters per second
coords = null;
}
// detects if geolocation is supported
if ( ! Geo ) { throw new Error("geolocation not available."); }
// Gets the current position once
Geo.getCurrentPosition(onPosition, onError, options);
// Returns the current position, then watches for change in position
watchId = Geo.watchPosition(onPosition, onError, options);
// Stops watching for position changes
Geo.clearWatch(watchId);
@paulirish
Copy link

Very nice.

It turns out you dont need to do a getCurrentPosition before you hit up watchPosition.. So you can dive right into that one.

I wrote more about it here: https://developer.mozilla.org/en/using_geolocation#Watching_the_current_position

@kara-ryli
Copy link
Author

Good point. This primer isn't intended to imply you need both, it's more of a syntax cheat sheet. Thanks for the feedback—I'll see if I can reword it.

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