Using HTML5 to Determine User Location

Geolocation is one of the most exciting features offered by HTML5.

Using some relatively simple JavaScript code, you can create Web applications that determine various aspects of the user location, including longitude, latitude and altitude plus more. Some Web applications can even provide navigation functionality by monitoring the user position over time, integrating with map systems such as Google Maps API.

As with all HTML5 functions, you cannot yet rely on browser support. Where browser support exists, it varies in depth and consistency. Essentially, you need to provide alternative functionality for users whose browsers do not fully support HTML5.

In this tutorial we’ll run through the basics of establishing user location. In practice, the browser may be getting its data from more than one possible source. For example it could be GPS data on a mobile device or simply IP address based data on any device connected to the Internet. However, your code does not need to concern itself with these details, you can simply retrieve and use the location data for the purposes of your own projects.

HTML5 Web Page

Use the following code to create an outline for your HTML5 page:

<!DOCTYPE html>
/*Location functions here*/

We will place the JavaScript Geolocation functions in the page head script section and some basic HTML elements for testing and demonstrating the functionality in the body section.

HTML Demonstration Elements

Add the following markup to your HTML body section:

<input type="button" value="get location" onclick="getUserLocation()"/>
<div id="locationData">
Location data here

You can call your Geolocation functions at any time, such as when the page loads, or in conjunction with jQuery document ready functions. To demonstrate, we’ll use the button to call the function and will write the location data into the div element, which has some simple placeholder text in it initially.

Get Position Function

The main method we will be using to determine user location is the getPosition method. Add the following function in the script section in your page head:

function getUserLocation() { 

//check if the geolocation object is supported, if so get position
if (navigator.geolocation)
	navigator.geolocation.getCurrentPosition(displayLocation, displayError);
	document.getElementById("locationData").innerHTML = "Sorry - your browser doesn't support geolocation!";

This function is called when the user clicks the button. The code first checks that the navigator Geolocation object is present, which means the browser supports it. If the Geolocation object is supported, the code uses it to call the getCurrentPosition method.

The getCurrentPosition method takes two parameters indicating callback functions. The first is a function to call when the Geolocation data is received, while the second is a function to call if an error is returned instead.

If the Geolocation object is not supported, the function simply writes an error message to the page div element.

When a site attempts to retrieve the user location data for the first time, the user’s browser will prompt them to determine whether or not they consent to share their data. The function will only proceed if they do consent.

Display Location Function

Next we need to implement the function we included as first parameter to the getCurrentPosition method call. This function will be passed the user location data when the browser receives it. Add the following after your getUserLocation function:

function displayLocation(position) { 

//build text string including co-ordinate data passed in parameter
var displayText = "User latitude is " + position.coords.latitude + " and longitude is " + position.coords.longitude;

//display the string for demonstration
document.getElementById("locationData").innerHTML = displayText;

This code first creates a variable in which it builds a string containing the longitude and latitude data from the location position parameter. The function then writes this to the page along with some informative text. In your own sites you can use the data for some more useful purpose, rather than writing it to the page – this is just for demonstration.

Error Function

There are many things that can go wrong when using the Geolocation facility. The user may not consent to sharing their location data, the browser may not be able to retrieve the data, there may be a timeout error some other unspecified problem. We therefore need to add a function to handle errors, using the name we specified as second parameter to the getCurrentPosition method. Add the following function after your displayLocation function:

function displayError(error) { 

//get a reference to the HTML element for writing result
var locationElement = document.getElementById("locationData");

//find out which error we have, output message accordingly
switch(error.code) {
	locationElement.innerHTML = "Permission was denied";
	locationElement.innerHTML = "Location data not available";
case error.TIMEOUT:
	locationElement.innerHTML = "Location request timeout";
case error.UNKNOWN_ERROR:
	locationElement.innerHTML = "An unspecified error occurred";
	locationElement.innerHTML = "Who knows what happened...";

This function receives the error data following the Geolocation position request. The function first gets a reference to the page div element to write the appropriate error message into. The message is tailored to the specific nature of the error using the switch statement.

Considerations and Options

The above functions cover the basics of retrieving user location data, but there is huge potential here. You can use the retrieved user position data to display the user’s location on a map through the Google Maps API,  basically by building the data variables into a custom URL and loading this into an HTML image element in your page.

You can also use the watchPostion method to track the user location and even speed as they move, although this is of limited accuracy where the data is not coming from GPS on a mobile device, for example if it is coming from wireless network data in the area.

These functions promise an interesting future for Web developers. However, their success is dependent not only on browser support, but also user preferences and hardware features. We’ll have to wait a little longer to really get the best of HTML5, but it’s certainly something to look forward to.

Sue Smith works as a Web/ software developer and technical writer based in the UK: see for details. Sue has written for various clients including Smashing Magazine and Mobiletuts+. She also does a little Android development and some comedy writing. More articles by Sue Smith
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress