Geolocation Introduction with HTML5

Posted on Tuesday June 12, 2012 / by Eric Potvin

Few years ago, we couldn't do (or think) what we can do today with our smart phone. These inseparable devices makes our life lazier but, let's be honest, we like it that way. As mobile traffic grows rapidly, we have to be updated on the latest technologies and make sure we use it right. This will not tells you all the new technologies (obviously) but a specific one called: Geolocation.

Before the arrival of this feature, we had to retrieve the client IP address, then using some database find out the location of the person. Well, this is something from the past now. by simply adding simple JavaScript, we can easily find out the Geolocation if, of course, the user allows it.

Geolocation can be very useful if you run a website that allow the user to interact with a map or find some kind of coupons/deals near them. This feature can be easily used on iPhone and Android with GPS hardware capability.

Here's how:


<button>Get my location</button>

  Latitude: <span id="lat"></span>
  Longitude: <span id="lon"></span>
<a href="#" target="google">Map This</a>


  $("button").click(function() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(processSuccess, processError);


function processSuccess(position) {
  var mapUrl = '' + position.coords.latitude + ',' + position.coords.longitude + '+%28My+Test%29&z=14&ll=' + position.coords.latitude + ',' + position.coords.longitude;
  $('a').attr('href', mapUrl);

function processError(err) {
    case error.TIMEOUT:
      alert ('Timeout');
      alert ('Unable to find the current position');
    case error.PERMISSION_DENIED:
      alert ('Permission denied by the user');
    case error.UNKNOWN_ERROR:
      alert ('Unknown error');

This will give you a message like:

geolocation screenshot iphone

Sorry, I only have the iPhone version

If the user allows this action, you will be able to determine the Geolocation (Latitude and Longitude) of where the user is located. In any other cases, like the user denied the request or a time-out occur, you can simply display an error message or anything that is useful to the user.