Just because you can, doesn't mean you should. Getting peoples exact loaction is an invasion of privacy unless they voluteer that information to you.

Luckly our browsers ask us if we want the website to see where we are.

What information can we access?

Once the website you are on asks for your permission to get your location, that is not the end of it. There are a number of steps involved in finding where you are. If it can find you via GPS it will, failing that it will go through a series of fallback options until either it gets your position or outright fails to get a lock on you.

Many things affect the accuracy of this position information, and we need to ensure we are covering every eventuality. The browser's navigation object holds the geolocation object, which in turn has access to a couple of methods in its prototype chain.

That is about as small as APIs get in the realm of HTML5.

Those two methods above are pretty similar. The watchPosition essentially calles getCurrentPosition over and over until you give up on "the stalking" with navigator.geolocation.clearWatch()

Getting the position information

Lets do a real example.

build Dev tools time build Look at the source and run GEOLOCATION.findMe(); or run this code below. The 2 callbacks are not a misprint.
function showPositionInfoOrError(position_or_error_object){
navigator.geolocation.getCurrentPosition(showPositionInfoOrError, showPositionInfoOrError);

bug_report Did you see a warning at the top of your browser? If so adjust your settings.

build Dev tools time build Try resetting your browser geolocation permissions for this site (click in the top left of the address bar), then refresh the page, and run GEOLOCATION.findMe(); again, but this time click 'block'.

Error Handling

If you did all that successfully you should see a differenet object. A position error object literal will be shown that holds these constant values.

Always handle errors don't just show a blank map to your users or hang the page indefinetly.

If you clicked deny you should see the error code integer of (you guessed it) 1. If you did nothing for long enough you will see 3. You get the idea. The hasOwnProperties of the position error object literal gives you a nice message incase you forget what the 3 codes represent and are too lazy to look up the chain for it.

code: 1
message: "User denied Geolocation"
build Dev tools time build See if you can trigger all the errors. I never seem to be able to trigger position unavailable, as I can't bring myslef to go offline...and risk misssing a tweet.

announcement Did you notice that the position object is retruned very quickly. Usually a second or so. I recommend when building a UI for use with this API that you experiment with the network speed setting under the Network tab in dev tools. Click no throttling and change it to pretend we are back in 2006. Don't forget to change it back after your done playing, or you might think your cable company is to blame.

The position object

Lets go back and have a look at a successful position object.

   coords: {
       accuracy: 72,
       altitude: null,
       altitudeAccuracy: null,
       heading: null,
       longitude: 99999999999999, // made up longitude
       latitude: 99999999999999, // made up latitude
       speed: null
   timestamp: 2134567891232 // made up timestamp

The timestamp can be converted easily.

var better_date_str = new Date(2134567891232).toLocaleDateString();
  // this blog is from the future "8/22/2037"

The accuracy tells you how good the lock is? If it is over a certain value, it may be useless. you should ask for a zip code instead. You are not going to get heading and speed unless you are moving.

build Dev tools time build Try this on your cellphone.

Click the radar icon up (once) at the top of this page, and wait a few moments for an alert to appear.

The accuracy tells you how good the lock is? If it is over a certain value, it may be useless. you should ask for a zip code instead. You are not going to get heading and speed unless you are moving.

Getting a map

If you have a position object we can get a map by using a third party API. Google Maps requires a dom element to display your location on. I have created such an object for you.

Run GEOLOCATION.mapMe(); (or click here once). In a few moments this element should see where you are on the map. I don't keep this info btw. Only you will see this map...don't worry.
This text will be replaced with a map once you call mapMe correctly.

If need to try this on your site, you will need 6 things:

  • 1) this js file below in your head
  • 2) some code to interface with it (see code block below)
  • 3) and element to use for the map
  • 4) some css that sizes your holder or it will be height 0 and you won't see it.
  • 5) a google maps API browser key (see this page html head source)
  • 6) [Pain in the butt alert] Enable via google console the staic maps API AND the maps API AND google maps embed API
.map_holder {
   width: 80%;
   height: 400px;
   border: 1px solid #B5BAAB;
   border-radius: 4px;
   margin: 12px auto;
 * showMap
 * This will show a google map 
 * on the element provided
 * @param JQUERY WRAPPER $area_to_show_map_on  //
 * @param Number lat_int // 23456723232
 * @param Number long_int // 3556723232
 * @param Number acc_int // 232323
 * @return Undefined
function _showMap($area_to_show_map_on, lat_int, long_int, acc_int){
    var my_lat_long = {
            lat: lat_int,
            lng: long_int
        my_options = {
            zoom: 14,
            center: my_lat_long,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        map = new$area_to_show_map_on.get(0), my_options),
        marker = new google.maps.Marker({
            position: my_lat_long,
            map: map,
            title: "Accuracy of " + acc_int + " meters"

FYI. You may get a message saying that google maps api needs keys. I do not have these set up. If you do not see anything int he map it means google have tighted up and not require keys. Simply grap my geolocation.js file in the source and add your keys.

Let me know how you get on with this and if you do anything cool with this.

My comments engine is day. For now, drop me an email if you have stuff to get off your chest