HTML5 Geolocation API – The basics

html5 geolocation api

Location, location, location. No, I am not writing about real estate but rather a new HTML5 API that empowers developers by giving them the ability to get the geographical location of a user. In this post, I will cover the basics of the API – mainly how to get started – and I have also put together a demo to boot. The demo shows your approximate current location.

Geolocation makes the user’s location co-ordinates available to JavaScript which can then send them back to the server. This information can then be used by the developer to personalize user experience and tailor content for the end user based on location. Many retail sites, for example, tap into the geolocation API in conjunction with the Google maps API to show the user a nearby store.

Note: The browser or device must get express permission from the user before disclosing their location.

All modern user agents, otherwise known as browsers, have implemented the API, albeit the implementation is still in flux. The browser or device must get express permission from the user before sending their location co-ordinates, which comes as a relief to many users who would rather not share their location with a web site or application.

Get current position

In its simplest form, the geolocation function is;
function getLocation(){

Unfortunately, since the API is not implemented across all browsers at the time of this writing, we have to make provisions for antiquated browsers. This is where a really handy feature detection library called Modernizr (If you are not using it, you should) comes to the rescue. We can use Modernizr to test for geolocation support, providing a fall back where the API is not supported. Let’s rewrite the above code;
function getLocation(){
    //no support, provide a fallback. Maybe


What happens behind the scenes

Remember for the browser to send the user’s location, the user must grant permission. So when you call getCurrentPosition() method the following happens;

  • The user will get a prompt alerting the user of the fact that the website wants to know their location
  • The prompt will request the user’s consent to share their location
  • The method is ‘blocking’ so the website cannot bypass it

Below is an example of a prompt you get in Chrome;

Getting the user’s co-ordinates

If the user consents to sharing their location, the callback (I have called mine showMap) will fire. The callback takes one argument which is an object that contains both the coordinates and a timestamp. Let’s write the showMap function;
function showMap(position){
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
//we can place the map on the canvas

The position object passed as a parameter in the showMap function consists of the following properties;

  • coords.latitude – degrees
  • coords.longitude – degrees
  • coords.altitude – meters
  • coords.accuracy – meters
  • coords.altitudeAccuracy – meters
  • coords.heading – degrees clockwise
  • coords.speed – meters per second
  • timestamp – similar to the Date() object

Now, working on the premise that geolocation works on a opt-in basis, we have to be prepared for some error-handling in the event that the users decides not to share their location. The second argument to our getCurrentPosition() method, is the error handling callback. So let’s update our function to that effect.
navigator.geolocation.getCurrentPosition(showMap, errHandler)

If there is a problem, the errHandler() callback will fire. The error handler has a PositionError object which is one of the following;

  • PERMISSION_DENIED(1) – The user has denied you access to their location
  • POSITION_UNAVAILABLE(2) – The network is down
  • TIMEOUT(3) – It took too long to calculate the user’s position

Above codes in hand, we can handle all three cases as we see fit. For example, if the user opts not to share their location, our error handler would be something like;
function errHandler(err){
  if(err.code == 1){
    //user said nada

The getCurrentPosition function takes a third optional argument called PositionOptions. This is an object with three properties namely; enableHighAccuracy, timeout and maximumAge. As you can deduce from their names, enableHighAccuracy provides as an accurate a result as possible. If set to true, this might however result in a slower response. Timeout is the number of milliseconds your application is willing to wait for a calculation, and maximumAge allows the application to use a cached position within a specified time frame. I illustrate one of the three optional properties below;
navigator.geolocation.getCurrentPosition(showMap, errHandler, {maximumAge:85000})

Cross browser support

Most modern browsers including IE9 and above support geolocation natively. However, if you are still supporting legacy IE (IE8 and below) do not despair. Help is at hand in the form of geoposition.js.


Geoposition.js is a geolocation polyfill that not only simulates the functionality in legacy IE, it also standardizes implementation across the numerous platforms, mobile included. To use the library, simply download the script from github and call it from within your document. Remember it is a best practise to add your scripts at the bottom of the body section even though technically, you should add them to the head section. While scripts are loading, they will stop the rest of the page from loading (also referred to as blocking). By adding them to the bottom of the page, you avoid this.

non-blocking geoposition script tag

<!doctype html>

  <script src="js/geoPosition.js"></script>

Once you have the script in place, you are now ready to use geolocation with assurances that it will work cross browser and cross platform.


To initialize geolocation, do the following;
  geoPosition.getCurrentPosition(successCallback, errCallback, {enableHighAccuracy:true})
  //geolocation is not available on this device or browser

We can now write the succesCallback and errCallback functions.

Success callback

function successCallback(p){
  //p : the the geolocation object as the passed argument
  //p.latitude : the latitude value
  //p.longitude : the longitude value value

Error callback

function errCallback(p){
  //p.message : the error message

The API is well documented on github, so if you are interested in all the bells and whistles, read the documentation.


To quickly demonstrate geolocation, if the user’s browser or device supports geolocation, I have added a simple link to this page and attached a click event listener. When the user clicks the link, the geolocation function is called and the magic happens. Otherwise, I simply display a “your browser doesn’t support geolocation” message. GIVE IT TRY!

Note: Remember to drop in at the google developers page to grab an API key which you will need use google maps in your projects.

That’s it people.

Useful resources

Leave a Reply

Your email address will not be published. Required fields are marked *