HTML5 GeoLocation in Web App Tutorial

Source

(c) 2013 kevin languedoc (klanguedoc)

GeoLocation is a feature of the HTML5 specification and API. GeoLocation can pinpoint the user’s location anywhere in the world. This is a very revolutionary and powerful API not only for location apps but also for marketers who might want to offer products, services and content specific the user’s location. In the past user location had to be requested or a generalized, high-level, location could be obtained from the user-agent header information. In contrast the GeoLocation API can pinpoint your exact location which be viewed in a map or used for some other function.

GeoLocation adds location based features that are ECMAScript compliant (Javascript). GeoLocation uses the Location Information Server (LIS) to locate and track information on a user (with their permission of course) which was set up by the National Emergency Number Association. This association manages e911 or 9-1-1 information globally. Other sources of information may include GPS, if available, RFID, the devices IP address, Wi-Fi identification. The API operates on a “best-effort” but doesn’t guarantee the exact location precision. Meaning that if you look at your position in a Google Map, the pinpoint may be off like most Map applications and services.

GeoLocation is ideal for mobile devices like smartphones and tablets and its accuracy increases if used in conjunction with a GPS, if the device has one. However the GeoLocation will also work from any computer with a supported browser. The following browsers are supported: Internet Explorer 9 and later, Safari 5 and later, Firefox 3.5 and later, Google Chrome and Opera 10.6.

How GeoLocation Works

The API for the GeoLocation determines your location and returns the latitude and longitude of your position if you allow it. The browser that the user is using must support GeoLocation others the use of the GeoLocation will either throw an error or won’t simply work. You can use the returned information with map applications like Google Maps to display a user’s location. The API can be used as a one-shot query, to query the browser cache, or repeated locations updates (like pinging).

The GeoLocation object is called from the navigator object in the DOM or from the window.navigator.

GeoLocation API

The GeoLocation API has several objects, properties and method. All of them are listed below for your convenience.

Methods

  • clearWatch. This method when used will stop the script from listening for new updates from the geographical location.
  • getCurrentLocation. Get the current location as latitude and longitude coordinates.
  • watchPosition. When you implement this method, GeoLocation will begin watching for updates from the client.


Properties

  • accuracy. This returns the accuracy in meters of the current position.
  • altitude. Returns the current altitude
  • altitudeAccuracy. Returns the accuracy of the current altitude in meters.
  • code. This property returns the error when the geographical location cannot be retrieved by the service.
  • coords. This property returns the coordinates for a location from the getCurrentPostion and positionWatch methods.
  • geolocation. Gets a handle on the geolocation object.
  • heading. Returns the direction of travel of client, if moving, in degrees.
  • latitude. This property returns the latitude in degrees of a coordinates object
  • longitude. This property returns the longitude in degrees of a coordinates object
  • message. Returns an error message if any. The error message can be a successful operation, like returning 0 to indicate that the operation completed successfully.
  • speed. The ground speed the device or client if in motion as meters per second.
  • timestamp. Gets the time when the location information was retrieved.

Objects

  • Coordinates. This object represents the geographic location coordinates.
  • GeoLocation. The GeoLocation is the main object in the API. It encapsulates all the methods and properties needed to obtain the devices and user’s location information if permission is granted.
  • Position. Same as Coordinates.
  • PositionError. The error information is the geographical information cannot be obtained.

Examples

This example demonstrates the getCurrentLocation as well as the startWatch and clearWatch methods. The code was written using Aptana with Firefox for debugging purposes. The index.html page was created using the HTML5 template. However I removed the jquery and google analytics code for the sake of clarity. The Javascript functions are in a separate file called geo.js. The code is provided below.

index.html in HTML5

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>GeoLocation</title>
        <meta name="description" content="This is a simple geographical application to demonstrate the GeoLocation
      API in HTML5">
        <meta name="viewport" content="width=device-width">

        <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <script src="js/vendor/modernizr-2.6.2.min.js"></script>
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
        <![endif]-->

        <!-- Add your site or application content here -->
         <p>The GeoLocation Example</p>
        <p>This is a simple geographical application to demonstrate the GeoLocation
      API in HTML5</p>

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

       
        
          <table border="1" style="width: 100%">
      <tbody>
        <tr>
          <td>Latitude: <input type="text" name="latitude" value="" disabled/></td>
          <td>Longitude: <input type="text" name="longitude" value="" disabled/></td>
        </tr>
        <tr>
          <td>Accuracy: <input type="text" name="accuracy" value="" disabled /></td>
          <td>Altitude: <input type="text" name="altitude" value="" disabled /></td>
        </tr>
        <tr>
          <td>Altitude Accuracy: <input type="text" name="altitudeAccuracy" value=""
              disabled /></td>
          <td>Speed: <input type="text" name="speed" value="" disabled /></td>
        </tr>
        <tr>
           <td>Heading:<input type="text" name="heading" value="" disabled/><br />
          </td>
          <td>Error Code:<input type="text" name="errorCode" value="" disabled /><br />
          </td>
        </tr>
        <tr>
         <td>Timestamp: <input type="text" name="timestamp" value="" disabled /><br />
          </td>
          <td>Error Message:<input type="text" name="errMsg" value="" disabled/><br />
          </td>
        </tr>
        <tr>
          
          <td><br />
          </td>
        </tr>
      </tbody>
    </table>
    <p> <button name="Start Watch" value="startWatch" onclick="startWatchPositon()">Start Watch</button> 
    	<button name="Stop Watch"value="stopWatch" onclick="stopWatchPosition()">Stop Watch</button> 
        <button name="Get Location" value="getLocation" onclick="getLocation()">Get
        Current Location</button> </p>
    <p> </p>
    </body>
</html>

geo.js

//global variables for fields
	var lat = document.getElementsByName('latitude');
	var lon = document.getElementsByName('longitude');
	var accuracy = document.getElementsByName('accuracy');
	var altAccuracy = document.getElementsByName('altitudeAccuracy');
	var altitude = document.getElementsByName('altitude');	
	var speed = document.getElementsByName('speed');	
	var heading = document.getElementsByName('heading');
	var coordinates = document.getElementsByName('coords');
	var code = document.getElementsByName('errorCode');	
	var codeMsg = document.getElementsByName('errMsg');	
	var time = document.getElementsByName('timestamp');	
	
	var watchId;

function getLocation(){
 if (navigator.geolocation)
	{
	navigator.geolocation.getCurrentPosition(getGeographicalPostion,
                                             errorHandler,
                                             {maximumAge:600000});
	
	}
  else{codeMsg.value="Geolocation is not supported by this browser.";
  }
  }
  
function getGeographicalPostion(position)
  {
  	
     lat[0].value = position.coords.latitude; 
	 lon[0].value = position.coords.longitude; 
	 accuracy[0].value = position.coords.accuracy; 
	 altAccuracy[0].value =position.coords.altitudeAccuracy; 
	 altitude[0].value = position.coords.altitude; 
	 speed[0].value = position.coords.speed; 
	 heading[0].value = position.coords.heading; 
	 time[0].value = position.timestamp; 
}

function errorHandler(error){
	
	code[0].value = error.code; 
	
}

function startWatchPositon(){
	watchId = navigator.startWatch(getGeographicalPostion,
                                             errorHandler);
	
}

function stopWatchPosition(watchId){
	navigator.geolocation.clearWatch(watchId);
}
Sample output from my Mac (stationary)
Sample output from my Mac (stationary) | Source

GeoLocation is an excellent API to fetching the coordinates of a user. With their permission of course. It is especially useful in mobile devices but as I mentioned it can be a powerful tool for providing products, services and geographical information to localized end users.

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working