Home > Articles, Internet Applications > HTML5 Geolocation simple example.

HTML5 Geolocation simple example.

In this article I’ll show you how you can use the HTML5 Geolocation API in order to get user’s location.

Here is the HTML5 boilerplate code (location.html) :

<!doctype html>

<html>
  <head>
    <meta charset="utf-8">
    
    <title>HTML5 Geolocation API.</title>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

    <script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script>

    <script src="location.js"></script>
  </head>
  <body>
    <p>Location :</p><div id="locationMessage"></div>
  </body>
</html>

Here is the Geolocation Javascript code (location.js) :

$(document).ready (function () {
  var locationMessage = $("#locationMessage");

  if (Modernizr.geolocation) {
    navigator.geolocation.getCurrentPosition (
      function (position) {
        var longitude = position.coords.longitude;
        var latitude = position.coords.latitude;

        locationMessage.text ("Lat: " + latitude + ", Lng: " + longitude);
      },
      function (error) {
        var errorTypes = {
          0: "Unknown error",
          1: "Permission denied by user",
          2: "Position is not available",
          3: "Request timed out"
        };

        var errorMessage = errorTypes[error.code];

        if (error.code == 0 || error.code == 2) {
          errorMessage += (": " + error.message);
        }

        locationMessage.text (errorMessage);
      });
  }
  else {
    locationMessage.text ("Geolocation support is not available.");
  }
});
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

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

%d bloggers like this: