ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

HTML5 GeoLocation in Web App Tutorial

Updated on January 6, 2013

(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.


  • 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.


  • 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.


  • 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.


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]-->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <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>
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="">upgrade your browser</a> or <a href="">activate Google Chrome Frame</a> to improve your experience.</p>

        <!-- 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%">
          <td>Latitude: <input type="text" name="latitude" value="" disabled/></td>
          <td>Longitude: <input type="text" name="longitude" value="" disabled/></td>
          <td>Accuracy: <input type="text" name="accuracy" value="" disabled /></td>
          <td>Altitude: <input type="text" name="altitude" value="" disabled /></td>
          <td>Altitude Accuracy: <input type="text" name="altitudeAccuracy" value=""
              disabled /></td>
          <td>Speed: <input type="text" name="speed" value="" disabled /></td>
           <td>Heading:<input type="text" name="heading" value="" disabled/><br />
          <td>Error Code:<input type="text" name="errorCode" value="" disabled /><br />
         <td>Timestamp: <input type="text" name="timestamp" value="" disabled /><br />
          <td>Error Message:<input type="text" name="errMsg" value="" disabled/><br />
          <td><br />
    <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>


//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)
  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,

function stopWatchPosition(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.


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)