Find Out Your Visitor’s Position Using HTML5 Geolocation

Posted: March 15, 2012 in Android Posts, Aspx.NET Posts, Courses, Java Posts, JavaScript Posts, Random Posts

Geolocation is a way for the user to retrieve their position and share where they are. This can be done in a few ways, by using a GPS as the one in your new smartphone or connected to your computer is the most precise method. But for users without GPS the browser will use your IP and or try to find nearby WLAN stations, however this is not as precise but gives some idea of where they are. Exactly how this is done is not a W3C standard and each browser have their own way to do it.

Even though geolocation is really complicated it’s quite easy for you to implement. In this tutorial I will show you how to retrieve the user’s position and display it on a map using Google Maps. So lets get started.

Step 1. Create the HTML layout

We start of by creating a simple HTML page containing three div tags. One for the current status, one to display the data retrieved and one for displaying the user’s position on a map.

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <title>HTML5 Geolocation</title>
  </head>
  <body onload="initialize()">
    <div id="status"></div>
    <div id="data"></div>
    <div id="map_canvas" style="width: 640px; height: 480px"></div>
  </body>
</html>

We also include the Google Maps API, it’s important to set sensors=false in the URL, otherwise Google will try to find out the user’s position for us.

The initialize function we’re calling on load will try to fetch the position for us.

Step 2. Retrieve the Position

Next it’s time to create our initialize function which will call the geolocation API to get the position data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Initialize geolocation
function initialize() {
  if (navigator.geolocation) {
    document.getElementById('status').innerHTML = 'Checking...';
    navigator.geolocation.getCurrentPosition(
      onSuccess,
      onError, {
        enableHighAccuracy: true,
        timeout: 20000,
        maximumAge: 120000
      });
  }
  else {
    document.getElementById('status').innerHTML = 'Geolocation not supported.';
  }
}

First we check if the browser actually supports geolocation. Browser who supports geolocation are Internet Explorer 9, Firefox 3.5+, Chrome 5+, Opera 10.6+ and Safari 5+. So it’s quite widely supported already, but if the user has an old browser we show them a message telling them that geolocation is not supported.

Next we set the status message to “Checking…” to tell the user that we’re trying to fetch the location data since this might take some time. Then we call navigator.geolocation.getCurrentPosition which will try to retrieve the user’s position, it calls the onSuccess function if it succeeds, otherwise it will call the onError. These functions will be created in the next two steps.

There’s also a few optional parameters to the getCurrentPosition function. These are enableHighAccuracy which tells the web browser to try using the clients GPS if possible, the default value for this is false. The timeout parameter tells the browser how long we’re ready to wait to get the position in milliseconds, the default value is infinite. Lastly we have the maximumAge parameter which tells the browser how old the position cache is allowed to be in milliseconds, the default value for maximumAge is 0 which turns off cache completely.

Since geolocation is a big privacy concern the W3C standards requires the user to agree to share their position before the location is sent to the website, so when we call the getCurrentPosition a information bar will be shown to the user where the user has to allow us to get the position, if the user denies the onError will be function will be called.

Tip

Don’t rely fully on getting the user’s location since the user might deny your site from retrieving the position or something might go wrong. Always have a fallback solution if retrieving the position is critical.

Step 3. On Success

Next we add an onSuccess function to our script section. This function will display the data received and call the loadMap function to load our map.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Map position retrieved successfully
function onSuccess(position) {
  var data = '';
  data += 'latitude: ' + position.coords.latitude + '<br/>';
  data += 'longitude: ' + position.coords.longitude + '<br/>';
  data += 'altitude: ' + position.coords.altitude + '<br/>';
  data += 'accuracy: ' + position.coords.accuracy + '<br/>';
  data += 'altitudeAccuracy: ' + position.coords.altitudeAccuracy + '<br/>';
  data += 'heading: ' + position.coords.heading + '<br/>';
  data += 'speed: ' + position.coords.speed + '<br/>';
  document.getElementById('data').innerHTML = data;
  loadMap(position.coords.latitude, position.coords.longitude);
}

This function is quite self explanatory, we build a string with the retrieved data found in the position variable and shows it to our user. You will always get the latitude, longitude and accuracy values but the rest is optional and will probably only be set if the user has a GPS which the data is retrieved from.

Lastly we call the loadMap function and give the latitude and longitude to show where the user is on a map.

Step 4. On Error

Since geolocation is quite complex a lot can go wrong and we need an error handler. There’s four different error codes, 0 is an unknown error, 1 occurs if you deny the browser from retrieving your location, 2 occurs if the browse somehow fails to retrieve the location and 3 if our timeout variable is too short and the timeout expired.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Error handler
function onError(err) {
  var message;
  switch (err.code) {
    case 0:
      message = 'Unknown error: ' + err.message;
      break;
    case 1:
      message = 'You denied permission to retrieve a position.';
      break;
    case 2:
      message = 'The browser was unable to determine a position: ' + error.message;
      break;
    case 3:
      message = 'The browser timed out before retrieving the position.';
      break;
  }
  document.getElementById('status').innerHTML = message;
}

This function is also quite easy to understand, we get the error as a parameter to our function and shows the user a message depending on the error code retrieved.

Step 5. Display the Map

Next we display a map in our map_canvas div. This has really nothing to do with the HTML5 geolocation. So I won’t explain this for you, but it shouldn’t be too hard to understand.

Tip

If you want to learn more about Google maps check out their API here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Integration with google maps
function loadMap(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
  var settings = {
    zoom: 14,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById('map_canvas'), settings);
  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: 'Your Position!'
  }); 
  document.getElementById('status').innerHTML = 'Position Found!';
}

That’s all for today. You can try out or download the finished code below.

Example

Try out the finished example here: Example.

Download

Download the source from here: Download

Advertisements
Comments
  1. Reblogged this on Justin Cooney – Programming Tips and commented:
    A very interesting article about writing HTML5 Geolocation written by Zeeshan Akhter

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s