Category: APIs

  • SSE API

    Server-Sent Events (SSE API)

    Server-sent events are a way of sending data from a server to a web page without requiring the page to refresh or make requests. These events are useful for creating real-time applications, such as chat, news feeds, or notifications. Using SSE, we can push DOM events continuously from our web server to the visitor’s browser.

    The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling. Server-sent events standardize how we stream data from the server to the client.

    How to Use SSE in Web Application?

    To use Server-sent events in a web application, we need to add an <eventsource> element to the document. The src attribute of the <eventsource> element should point to an URL that provides a persistent HTTP connection that sends a data stream containing the events. Furthermore, the URL points to a PHP, PERL, or any Python script that would take care of sending event data consistently.

    Instance

    Following is a sample HTML code of a web application that would expect server time:

    <!DOCTYPE html><html><head><script type="text/javascript">
    
      /* Define event handling logic here */
    </script></head><body><div id="sse"><eventsource src="/cgi-bin/ticker.cgi" /></div><div id="ticker"><TIME></div></body></html>

    Server-side Script for SSE

    The following are the steps for sending server-sent events (SSE) from a server-side script:

    1. Set the Content-Type Header

    A server-side script should send Content-Type header specifying the type text/event-stream as follows.

    print "Content-Type: text/event-stream\n\n";
    

    2. Send an Event Name

    After setting Content-Type, the server-side script would send an Event: tag followed by the event name. Following code snippet would send Server-Time as an event name terminated by a new line character.

    print "Event: server-time\n";
    

    3. Send Event Data

    The final step is to send event data using Data: tag which would be followed by an integer of a string value terminated by a new line character as follows −

    $time = localtime();
    print "Data: $time\n";
    

    4. Combine Steps into a Complete Script

    Finally, following is a complete “ticker.cgi” written in Perl −

    #!/usr/bin/perlprint"Content-Type: text/event-stream\n\n";while(true){print"Event: server-time\n";$time= localtime();print"Data: $time\n";
       sleep(5);}

    Handle Server-Sent Events

    You can also modify the web application to listen for and process server-sent events using an eventsource object. Let us modify our web application to handle server-sent events.

    Example

    The following example demonstrates handling server-sent events:

    <!DOCTYPE html><html><head><script type="text/javascript">
    
      document.getElementsByTagName("eventsource")[0].addEventListener("server-time", eventHandler, false);
         function eventHandler(event) {
            // Alert time sent by the server
            document.querySelector('#ticker').innerHTML = event.data;
         }
    &lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;div id="sse"&gt;&lt;eventsource src="/cgi-bin/ticker.cgi" /&gt;&lt;/div&gt;&lt;div id="ticker" name="ticker"&gt; [TIME] &lt;/div&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Note: Before testing Server-Sent events, I would suggest that you make sure your web browser supports this concept.

  • Web Storage

    Web Storage

    HTML Web storage is a mechanism used for storing structured data on the client side without sending it to the server. These two storage mechanisms are session storage and local storage. Both are collectively part of the HTML5 Web Storage API.

    Need of Web Storage

    HTML Web storage was introduced to overcome the following drawbacks of cookies:

    • Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data.
    • Cookies are included with every HTTP request, thereby sending data unencrypted over the internet.
    • Cookies are limited to about 4 KB of data. Not enough to store required data.

    Types of Web Storage

    HTML provides two types of web storage:

    • Session storage
    • Local storage

    To use these two web storages (session storage or local storage) in your web application, you can access them through the window.sessionStorage and window.localStorage properties, respectively.

    The Session Storage

    The session storage is temporary, and it gets cleared when the page session ends, which happens when the browser tab or window is closed. The data stored in session storage is specific to each tab or window.

    HTML5 introduces the sessionStorage attribute, which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window, i.e., session, and as soon as you close the window, the session would be lost.

    Example

    Following is the code that would set a session variable and access that variable −

    <!DOCTYPE html><html><body><script type="text/javascript">	
    
      if( sessionStorage.hits ){
         sessionStorage.hits = Number(sessionStorage.hits) +1;
      } else {
         sessionStorage.hits = 1;
      }
      document.write("Total Hits :" + sessionStorage.hits );
    </script><p>Refresh the page to increase number of hits.</p><p>Close the window and open it again and check the result.</p></body></html>

    Local Storage

    The local storage is designed for storage that spans multiple windows and lasts beyond the current session. It does not expire and remains in the browser until it is manually deleted by the user or by the web application. In particular, web applications may wish to store megabytes of user data, such as entire user-authored documents or a user’s mailbox, on the client side for performance reasons.

    Again, cookies do not handle this case well because they are transmitted with every request.

    HTML5 introduces the localStorage attribute, which would be used to access a page’s local storage area without a time limit, and this local storage will be available whenever you use that page.

    Example

    Following is the code that would set a local storage variable and access that variable every time this page is accessed, even next time, when you open the window −

    <!DOCTYPE html><html><body><script type="text/javascript">
    
      if( localStorage.hits ){
         localStorage.hits = Number(localStorage.hits) +1;
      } else {
         localStorage.hits = 1;
      }
      document.write("Total Hits :" + localStorage.hits );
    </script><p>Refresh the page to increase number of hits.</p><p>Close the window and open it again and check the result.</p></body></html>

    Delete Web Storage

    Storing sensitive data on a local machine could be dangerous and could leave a security hole. The session storage data would be deleted by the browsers immediately after the session gets terminated.

    However, to clear a local storage setting, we need to call localStorage.remove(‘key’), where ‘key’ is the key of the value we want to remove. If we want to clear all settings, the localStorage.clear() method can be called.

    Example

    Following is the code that would clear complete local storage −

    <!DOCTYPE html><html><body><script type="text/javascript">
    
      localStorage.clear();
      
      // Reset number of hits.
      if( localStorage.hits ){
         localStorage.hits = Number(localStorage.hits) +1;
      } else {
         localStorage.hits = 1;
      }
      document.write("Total Hits :" + localStorage.hits );
    </script><p>Refreshing the page would not to increase hit counter.</p><p>Close the window and open it again and check the result.</p></body></html>
  • WebSockets

    WebSockets is a next-generation bidirectional communication technology for web applications that operates over a single socket.

    WebSockets allow bidirectional communication, which means both client and server can send data to each other independently and simultaneously.

    After establishing a Web Socket connection with the web server, we can send data from browser to server by calling the send() method and receive data from server to browser by an onmessage event handler.

    Syntax

    Following is the API, which creates a new WebSocket object:

    var Socket = new WebSocket(url, [protocol] );
    

    Here the first argument, url, specifies the URL to which to connect. The second attribute, protocol, is optional and, if present, specifies a sub-protocol that the server must support for the connection to be successful.

    Attributes of WebSocket

    Following are the attributes of the WebSocket object. Assuming we created a socket object as mentioned above:

    AttributeDescription
    Socket.readyStateThe readonly attribute readyState represents the state of the connection. It can have the following values:A value of 0 indicates that the connection has not yet been established.A value of 1 indicates that the connection is established and communication is possible.A value of 2 indicates that the connection is going through the closing handshake.A value of 3 indicates that the connection has been closed or could not be opened.
    Socket.bufferedAmountThe readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using the send() method.

    WebSocket Events

    Following are the events associated with the WebSocket object. Assuming we created a socket object as mentioned above:

    EventValues & Event HandlerValues & Description
    openSocket.onopenThis event occurs when socket connection is established.
    messageSocket.onmessageThis event occurs when client receives data from server.
    errorSocket.onerrorThis event occurs when there is any error in communication.
    closeSocket.oncloseThis event occurs when connection is closed.

    WebSocket Methods

    Following are the methods associated with the WebSocket object. Assuming we created a socket object as mentioned above:

    MethodDescription
    Socket.send()The send(data) method transmits data using the connection.
    Socket.close()The close() method would be used to terminate any existing connection.

    Setting Up the WebSocket Server with Python

    Step 1. Install PythonIf you don’t have Python installed on your device, download and install it from Python.orgStep 2. Install WebSocket libraryAfter installing python create a folder for your project, and open that folder in the command prompt or terminal. Then run this prompt.

    pip install websockets
       

    Step 3. Create the websocket serverOpen any text editor and write the below Python code. Then save that as a file in the folder with the name ‘server.py’

    import asyncio
    import websockets
    
    asyncdefecho(websocket, path):asyncfor message in websocket:print(f"Received message: {message}")await websocket.send(f"Server: You said \"{message}\"")
    
    start_server = websockets.serve(echo,"localhost",8080)
    
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

    Step 4. Run the serverIn the terminal navigate to your project folder, and run this command to start server.

    python server.py
    

    Setting up HTML Client for the Server

    So far we setup a Python server for websocket. The server will be running on your terminal, so any messages sent to the server will be visible at the terminal. Here we will see how to setup a client that can receive messages from the server and also send messages to the server using HTML and JavaScript.

    Create an HTML file ‘index.html’ in the folder.

    <!DOCTYPE html><html lang="en"><head><title>WebSocket Example</title></head><body><h1>WebSocket Client</h1><input type="text" 
    
          id="messageInput" 
          placeholder="Type a message..." /&gt;&lt;button id="sendButton"&gt;
      Send
    </button><div id="messages"></div><script>
      const socket = new WebSocket('ws://localhost:8080');
      socket.addEventListener('open', 
      () =&gt; {
      console.log('Connected to server');
      });
      socket.addEventListener('message', 
      (event) =&gt; {
      const messageDiv = document.createElement('div');
      messageDiv.textContent = event.data;
      document.getElementById('messages').appendChild(messageDiv);
      });
      document.getElementById('sendButton').addEventListener('click', 
      () =&gt; {
      const messageInput = document.getElementById('messageInput');
      const message = messageInput.value;
      socket.send(message);
      messageInput.value = '';
      });
    </script></body></html>

  • Web Workers API

    The HTML Web Workers API is a JavaScript feature that is used to run computationally intensive tasks in background in a separate thread without interrupting the user interface.

    In this Web Workers API chapter, you will learn the following topics:

    • What Are Web Workers?
    • Need of Web Workers
    • How Web Workers Work?
    • Stopping Web Workers
    • Handling Web Workers Errors
    • Browser Support of Web Workers

    What Are Web Workers?

    • Web workers allows long tasks to be executed without yielding to keep the page unresponsive.
    • Web workers are background scripts, and they are relatively heavy-weight and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four-megapixel image.
    • When a script is executing inside a Web worker, it cannot access the web page’s window object (window.document).
    • Web workers don’t have direct access to the web page and the DOM API. Although Web workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.

    Need of Web Workers

    JavaScript was designed to run in a single-threaded environment, meaning multiple scripts cannot run at the same time. Consider a situation where you need to handle UI events, query and process large amounts of API data, and manipulate the DOM. JavaScript will hang your browser in situations where CPU utilization is high.

    Example

    Let us take a simple example where JavaScript goes through a big loop. Your browser will become unresponsive when you run this code:

    <!DOCTYPE html><html><head><title>Big for loop</title><script>
    
      function bigLoop() {
         for (var i = 0; i &lt;= 10000000000; i += 1) {
            var j = i;
         }
         alert("Completed " + j + "iterations");
      }
      function sayHello() {
         alert("Hello sir....");
      }
    </script></head><body><input type="button"
          onclick="bigLoop();" 
          value="Big Loop" /&gt;&lt;input type="button" 
          onclick="sayHello();" 
          value="Say Hello" /&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    The situation explained above can be handled using Web Workers, which will do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads.

    How Web Workers Work?

    Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will execute. This code sets event listeners and communicates with the script that spawned it from the main page. Following is the simple syntax:

    var worker = new Worker('bigLoop.js');
    

    If the specified JavaScript file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. If the path to our worker returns a 404 error, the worker will fail silently.

    If our application has multiple supporting JavaScript files, we can import them using the importScripts() method, which takes file name(s) as argument separated by comma as follows:

    importScripts("helper.js", "anotherHelper.js");
    

    Once the Web Worker is spawned, communication between the web worker and its parent page is done using the postMessage() method. Depending on the browser/version, the postMessage() method can accept either a string or JSON object as its single argument.

    The message passed by Web Worker is accessed using onmessage event in the main page. Below is the main page (hello.htm) which will spawn a web worker to execute the loop and to return the final value of variable j:

    Example

    <!DOCTYPE html><html><head><title>Big for loop</title><script>
    
      var worker = new Worker('bigLoop.js');
      worker.onmessage = function(event) {
         alert("Completed " + event.data + "iterations");
      };
      function sayHello() {
         alert("Hello sir....");
      }
    </script></head><body><input type="button"
          onclick="sayHello();" 
          value="Say Hello" /&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    Following is the content of bigLoop.js file. This makes use of postMessage() API to pass the communication back to main page:

    for (var i = 0; i <= 1000000000; i += 1){
       var j = i;
    }
    postMessage(j);
    

    The j variable from bigLoop.js is published using function postMessage(), Which then received at hello.htm using event attribute of worker.onmessage = function(event) {}

    Stopping Web Workers

    Web Workers don't stop by themselves, but the page that started them can stop them by calling the terminate() method.

    worker.terminate();
    

    A terminated Web Worker will no longer respond to messages or perform any additional computations. We cannot restart a worker; instead, we need to create a new worker using the same URL.

    Handling Web Workers Errors

    You can handle errors that occur in the Web Worker from the main thread by using the worker.onerror() method.

    Example

    The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console. With error handling code, the above example would become as follows:

    <!DOCTYPE html><html><head><title>Big for loop</title><script>
    
      var worker = new Worker('bigLoop.js');
      worker.onmessage = function(event) {
         alert("Completed " + event.data + "iterations");
      };
      worker.onerror = function(event) {
         console.log(event.message, event);
      };
      function sayHello() {
         alert("Hello sir....");
      }
    </script></head><body><input type="button"
          onclick="sayHello();" 
          value="Say Hello" /&gt;&lt;/body&gt;&lt;/html&gt;</pre>

    You can use the following code snippets as an error handler for the worker on the main page:

    worker.onerror = function(event) {
       console.error("Error in web worker: " + event.message, event);
       alert("Error occurred in the web worker.");
       // Prevents the default handling of the error
       event.preventDefault(); 
    };
    

    Checking for Browser Support

    To check the browser support for Web Workers, you can use Modernizr's webworkers feature test.

    Example

    Following is the syntax to detect a Web Worker feature support available in a browser:

    <!DOCTYPE html><html><head><title>Big for loop</title><script src="/js/modernizr-1.5.min.js"></script><script>
    
      if (Modernizr.webworkers) {
         alert("You have web workers support.");
      } else {
         alert("You do not have web workers support.");
      }
    </script></head><body><p>
      Checking for Browser Support for web workers
    </p></body></html>
  • Drag and Drop API

    Drag and Drop API

    Drag and Drop (DnD) is a powerful user interface concept that makes it easy to copy, reorder, and delete items with the help of mouse clicks and movements. This allows the user to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.

    To achieve drag-and-drop functionality with traditional HTML4, developers either have to use complex JavaScript programming or other JavaScript frameworks like jQuery, etc.

    Now, HTML5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser, making it much easier to code up. It is supported by all the major browsers, like Chrome, Firefox 3.5, Safari 4, etc.

    Creating an HTML Element Draggable

    You can create an HTML element draggable by using the draggable attribute with that specific element. Set the “true” value to the draggable attribute to make any HTML element, such as images, divs, files, or links, drag-enabled.

    Syntax

    The following syntax demonstrates making a div element draggable:

    <div draggable="true">

    Drag and Drop Events

    There are a number of events that are fired during various stages of the drag-and-drop operation. These events are listed below −

    Sr.No.Events & Description
    1dragstartFires when the user starts dragging of the object.
    2dragenterFired when the mouse is first moved over the target element while a drag is occurring. A listener for this event should indicate whether a drop is allowed over this location. If there are no listeners, or the listeners perform no operations, then a drop is not allowed by default.
    3dragoverThis event is fired as the mouse is moved over an element when a drag is occurring. Much of the time, the operation that occurs during a listener will be the same as the dragenter event.
    4dragleaveThis event is fired when the mouse leaves an element while a drag is occurring. Listeners should remove any highlighting or insertion markers used for drop feedback.
    5dragFires every time the mouse is moved while the object is being dragged.
    6dropThe drop event is fired on the element where the drop was occurred at the end of the drag operation. A listener would be responsible for retrieving the data being dragged and inserting it at the drop location.
    7dragendFires when the user releases the mouse button while dragging an object.

    Note − Note that only drag events are fired; mouse events such as mousemove are not fired during a drag operation.

    The DataTransfer Object

    The event listener methods for all the drag-and-drop events accept the Event object, which has a readonly attribute called dataTransfer.

    The event.dataTransfer returns the DataTransfer object associated with the event as follows:

    function EnterHandler(event) {
       DataTransfer dt = event.dataTransfer;
       .............
    }
    

    The DataTransfer object holds data about the drag and drop operation. This data can be retrieved and set in terms of various attributes associated with the DataTransfer object, as explained below −

    S.No.Attribute & Description
    1dataTransfer.dropEffect [ = value ]Returns the kind of operation that is currently selected.This attribute can be set, to change the selected operation.The possible values are none, copy, link, and move.
    2dataTransfer.effectAllowed [ = value ]Returns the kinds of operations that are to be allowed.This attribute can be set, to change the allowed operations.The possible values are none, copy, copyLink, copyMove, link, linkMove, move, all and uninitialized.
    3dataTransfer.typesReturns a DOMStringList listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string “Files”.
    4dataTransfer.clearData ( [ format ] )Removes the data of the specified formats. Removes all data if the argument is omitted.
    5dataTransfer.setData(format, data)Adds the specified data.
    6data = dataTransfer.getData(format)Returns the specified data. If there is no such data, returns the empty string.
    7dataTransfer.filesReturns a FileList of the files being dragged, if any.
    8dataTransfer.setDragImage(element, x, y)Uses the given element to update the drag feedback, replacing any previously specified feedback.
    9dataTransfer.addElement(element)Adds the given element to the list of elements used to render the drag feedback.

    Drag and Drop Process

    Following are the steps to be carried out to implement Drag and Drop operation −

    Step 1 − Making an Object Draggable

    Here are steps to be taken −

    • If you want to drag an element, you need to set the draggable attribute to true for that element.
    • Set an event listener for dragstart that stores the data being dragged.
    • The event listener dragstart will set the allowed effects (copy, move, link, or some combination).

    Example

    Following is an example of making an object draggable −

    <!DOCTYPE html><html><head><style type="text/css">
    
      #boxA,
      #boxB {
         float: left;
         padding: 10px;
         margin: 10px;
         -moz-user-select: none;
      }
      #boxA {
         background-color: #6633FF;
         width: 75px;
         height: 75px;
      }
      #boxB {
         background-color: #FF6699;
         width: 150px;
         height: 150px;
      }
    </style><script type="text/javascript">
      function dragStart(ev) {
         ev.dataTransfer.effectAllowed = 'move';
         ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
         ev.dataTransfer.setDragImage(ev.target, 0, 0);
         return true;
      }
    </script></head><body><center><h2>Drag and drop HTML5 demo</h2><div>Try to drag the purple box around.</div><div id="boxA" draggable="true" ondragstart="return dragStart(event)"><p>Drag Me</p></div><div id="boxB">Dustbin</div></center></body></html>

    Step 2 − Dropping the Object

    To accept a drop, the drop target has to listen to at least three events.

    • The dragenter event, which is used to determine whether or not the drop target is to accept the drop. If the drop is to be accepted, then this event has to be canceled.
    • The dragover event, which is used to determine what feedback is to be shown to the user. If the event is canceled, then the feedback (typically the cursor) is updated based on the dropEffect attribute’s value.
    • Finally, the drop event, which allows the actual drop to be performed.

    Example

    Following is an example of dropping an object into another object −

    <!DOCTYPE html><html><head><style type="text/css">
    
      #boxA,
      #boxB {
         float: left;
         padding: 10px;
         margin: 10px;
         -moz-user-select: none;
      }
      #boxA {
         background-color: #6633FF;
         width: 75px;
         height: 75px;
      }
      #boxB {
         background-color: #FF6699;
         width: 150px;
         height: 150px;
      }
    </style><script type="text/javascript">
      function dragStart(ev) {
         ev.dataTransfer.effectAllowed = 'move';
         ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
         ev.dataTransfer.setDragImage(ev.target, 0, 0);
         return true;
      }
      function dragEnter(ev) {
         event.preventDefault();
         return true;
      }
      function dragOver(ev) {
         return false;
      }
      function dragDrop(ev) {
         var src = ev.dataTransfer.getData("Text");
         ev.target.appendChild(document.getElementById(src));
         ev.stopPropagation();
         return false;
      }
    </script></head><body><center><h2>Drag and drop HTML5 demo</h2><div>Try to move the purple box into the pink box.</div><div id="boxA" draggable="true" ondragstart="return dragStart(event)"><p>Drag Me</p></div><div id="boxB" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" ondragover="return dragOver(event)">Dustbin</div></center></body></html>
  • Geolocation API

    HTML Geolocation API is used by web applications to access the geographical location of the user. Most modern browsers and mobile devices support the Geolocation API.

    JavaScript can capture your latitude and longitude and can be sent to a backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.

    Syntax

    var geolocation = navigator.geolocation;

    The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.

    Geolocation API Methods

    The Geolocation API provides the following methods:

    MethodDescription
    getCurrentPosition()This method retrieves the current geographic location of the user.
    watchPosition()This method retrieves periodic updates about the current geographic location of the device.
    clearWatch()This method cancels an ongoing watchPosition call.

    Example

    Following is a sample code to use any of the above methods:

    functiongetLocation(){var geolocation = navigator.geolocation;
       geolocation.getCurrentPosition(showLocation, errorHandler);
    
       watchId = geolocation.watchPosition(showLocation, errorHandler,{
    
      enableHighAccuracy:true,
      timeout:5000,
      maximumAge:0});
    navigator.geolocation.clearWatch(watchId);}

    Here, showLocation and errorHandler are callback methods that would be used to get the actual position as explained in the next section and to handle errors if there are any.

    Location Properties

    Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information.

    The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.

    The following table describes the properties of the Position object. For the optional properties, if the system cannot provide a value, the value of the property is set to null.

    PropertyTypeDescription
    coordsobjectsSpecifies the geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.
    coords.latitudeNumberSpecifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00].
    coords.longitudeNumberSpecifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00].
    coords.altitudeNumber[Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid.
    coords.accuracyNumber[Optional] Specifies the accuracy of the latitude and longitude estimates in meters.
    coords.altitudeAccuracyNumber[Optional] Specifies the accuracy of the altitude estimate in meters.
    coords.headingNumber[Optional] Specifies the device’s current direction of movement in degrees counting clockwise relative to true north.
    coords.speedNumber[Optional] Specifies the device’s current ground speed in meters per second.
    timestampdateSpecifies the time when the location information was retrieved and the Position object was created.

    Example

    Following is a sample code that makes use of the “position” object. Here, the showLocation() method is a callback method:

    functionshowLocation(position){var latitude = position.coords.latitude;var longitude = position.coords.longitude;...}

    Handling Errors

    Geolocation is complicated, and it is very much required to catch any error and handle it gracefully.

    The geolocation methods getCurrentPosition() and watchPosition() make use of an error handler callback method that gives a PositionError object. This object has the following two properties:

    PropertyTypeDescription
    codeNumberContains a numeric code for the error.
    messageStringContains a human-readable description of the error.

    The following table describes the possible error codes returned in the PositionError object.

    CodeConstantDescription
    0UNKNOWN_ERRORThe method failed to retrieve the location of the device due to an unknown error.
    1PERMISSION_DENIEDThe method failed to retrieve the location of the device because the application does not have permission to use the Location Service.
    2POSITION_UNAVAILABLEThe location of the device could not be determined.
    3TIMEOUTThe method was unable to retrieve the location information within the specified maximum timeout interval.

    Example

    Following is a sample code that makes use of the PositionError object. Here errorHandler method is a callback method:

    functionerrorHandler(err){if(err.code ==1){// access is denied}...}

    Position Options

    Following is the actual syntax of the getCurrentPosition() method:

    getCurrentPosition(callback, ErrorCallback, options)

    Here, the third argument is the PositionOptions object, which specifies a set of options for retrieving the geographic location of the device.

    Following are the options that can be specified as a third argument:

    PropertyTypeDescription
    enableHighAccuracyBooleanSpecifies whether the widget wants to receive the most accurate location estimate possible. By default, this is false.
    timeoutNumberThe timeout property is the number of milliseconds your web application is willing to wait for a position.
    maximumAgeNumberSpecifies the expiry time in milliseconds for cached location information.

    Example

    Following is a sample code that shows how to use above-mentioned methods:

    functiongetLocation(){var geolocation = navigator.geolocation;
       geolocation.getCurrentPosition(showLocation, 
    
                                  errorHandler,{maximumAge:75000});}</pre>

    Examples of HTML Geolocation API

    Here are some examples that show how to access geolocation in HTML:

    Get Current Location

    The following code shows how to access the current location of your device using JavaScript and HTML.

    <!DOCTYPE html><html><head><title>
    
         Geolocation API Example
      &lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h2&gt;Geolocation API Example&lt;/h2&gt;&lt;p id="demo"&gt;
      Click the button to get your coordinates:
    </p><button onclick="getLocation()">
      Show Location
    </button><script>
      var x = document.getElementById("demo");
      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
         } else {
            x.innerHTML = 
            "Geolocation is not supported by this browser.";
         }
      }
      function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude + 
         "&lt;br&gt;Longitude: " + position.coords.longitude;
      }
         
    </script></body></html>

    Error Handling in Geolocation

    Following is a sample code that shows how to use the above-mentioned methods:

    <!DOCTYPE html><html><head><title>Geolocation API Example</title></head><body><h2>Geolocation API Example</h2><p id="demo">
    
      Turn off location service of your device, 
      See how the error is handled.
    </p><button onclick="getLocation()">
      Show Location
    </button><script>
      var x = document.getElementById("demo");
      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
         } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
         }
      }
      function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude + 
         "&lt;br&gt;Longitude: " + position.coords.longitude;
      }
      function showError(error) {
         switch(error.code) {
            case error.PERMISSION_DENIED:
                  x.innerHTML = 
                  "User denied the request for Geolocation.";
                  break;
            case error.POSITION_UNAVAILABLE:
                  x.innerHTML = 
                  "Location information is unavailable.";
                  break;
            case error.TIMEOUT:
                  x.innerHTML = 
                  "The request to get user location timed out.";
                  break;
            case error.UNKNOWN_ERROR:
                  x.innerHTML = 
                  "An unknown error occurred.";
                  break;
         }
      }
    </script></body></html>

    Supported Browsers

    APIChromeEdgeFirefoxSafariOpera
    GeolocationYes9.03.55.016.0