Barbarian Meets Coding
barbarianmeetscoding

WebDev, UX & a Pinch of Fantasy

1 minute read

HTML5 Geolocation API

HTML5 provides a geolocation api that allows the user to provide their location to web applications. The api entry point is the navigator.geolocation object.

This object has three methods:

  • getCurrentPosition: get the user current position
  • watchPosition: allows you to specify an event handler for whenever the user position changes
  • clearWatch: removes an event handler from following the user’s position

To get the user’s position you can use the getCurrentPosition method as depicted below:

// getCurrentPosition(success, error, options)

var options = {
    enableHighAccuracy: true,
    timeout: 2000,
    maximumAge: 0 // caching configuration, 0 means no caching
}

if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(/* success */function(position){
       var coords = position.coords;
       console.log("Your position is: ", coords.latitute, coords.longitude, " with more or less ", coords.accuracy, " meters accuracy." );
    }, /* error */ function(e){
        console.error("there was an error!! ", e);
    }, options);
    
}

You can use the watchPosition to register an event handler for every time the user position changes:

// watchPosition(success, error, options) (same as getCurrentPosition)

var handlerId = navigator.geolocation.watchPosition(function(pos){
    // do something with position
})

if (iGetTired){
    navigator.geolocation.clearWatch(handlerId);
}

The Position object returned by the geolocation api has the following properties:

  • coords
    • latitute
    • longitude
    • altitude
    • accuracy
    • altitudeAccuracy
    • heading
    • speed
  • timestamp

Jaime González García

Written by Jaime González García , dad, husband, software engineer, ux designer, amateur pixel artist, tinkerer and master of the arcane arts. You can also find him on Twitter jabbering about random stuff.Jaime González García