Barbarian Meets Coding

WebDev, UX & a Pinch of Fantasy

1 minute read

HTML5 Geolocation API

This article is part of my personal wiki where I write personal notes while I am learning new technologies. You are welcome to use it for your own learning!

HTML5 provides a new geolocation api that allows the user to provide his/her 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){

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, Front-end software engineer, UX designer, amateur pixel artist, tinkerer and master of the arcane arts. You should follow him on Twitter where he shares useful stuff! (and is funny too).Jaime González García