HTML Geolocation

The Geolocation, an HTML5 API, is utilized to determine the geographical location of a user for web applications.

This latest addition in HTML5 provides the capability to access the latitude and longitude coordinates of the current visitor to a website. These coordinates can be obtained using JavaScript and then transmitted to the server to display the visitor's current location on the website.

The majority of geolocation services rely on network routing identifiers like IP addresses, RFID, WIFI and MAC addresses, or internal GPS devices to determine the location of the user.

Tips: To completely understand the concept of Geolocation API you must have some knowledge of JavaScript.

User privacy:

Protecting the privacy of users is a significant consideration when it comes to their location. To safeguard user privacy, the geolocation API ensures that it obtains explicit permission from the user before accessing their location data. This process involves displaying a notification prompt box to the user, giving them the option to either grant or deny access. Only if the user chooses to grant permission will their location be determined.

Note: Your browser must support the geolocation to use it for the web application. Although most of the browsers and mobile devices support the Geolocation API, and this API is only available for HTTPS request.

Geolocation object

The Geolocation API interacts with the navigation.geolocation object. Through its read-only property, it provides a Geolocation object that pinpoints the user's location and enables the creation of personalized outcomes tailored to the user's whereabouts.

Syntax:

Example

geo=navigator. geolocation;

Having this object available enables access to geolocation services.

Geolocation Methods

The Geolocation API employs three methods from the Geolocation interface, as outlined below:

Methods Description
getCurrentPosition() It identifies the device or the user's current location and returns a position object with data.
watchPosition() Return a value whenever the device location changes.
clearWatch() It cancels the previous watchPosition() call

Checking for browser support:

The geolocation feature within the navigator.geolocation object is utilized to ascertain the browser's compatibility with the Geolocation API.

Example

<!DOCTYPE html>

<html>

<head>

	<title>Geolocation API</title>

</head>

<body>

  <h1>Find your Current location</h1>

<button onclick="getlocation()">Click me</button>

<div id="location"></div>

<script>

	var x= document.getElementById("location");

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    function getlocation() {

    	if(navigator.geolocation){

    		alert("your browser is supporting Geolocation API")

    	}

    	else

    	{

    		alert("Sorry! your browser is not supporting")

    	}

    }

</script>

</body>

</html>

Getting the User's current position:

To get the user's current location, getCurrentPosition method of the navigator.geolocation object is used. This method accepts three parameters:

  • success: A success callback function to get the location of the user
  • error: An error callback function which takes "Position Error" object as input.
  • options: It defines various options for getting the location.

The following example demonstrates how to retrieve the longitude and latitude of the user's present location.

Example

Example

<!DOCTYPE html>

<html>

<head>

<title>Geolocation API</title>

</head>

<body>

  <h1>Find your Current location</h1>

<button onclick="getlocation()">Click me</button>

<div id="location"></div>

<script>

	var x= document.getElementById("location");

    function getlocation() {

    	if(navigator.geolocation){

    		navigator.geolocation.getCurrentPosition(showPosition)

    	  }

    	else

    	{

             alert("Sorry! your browser is not supporting")

         } }

     

     function showPosition(position){

       var x = "Your current location is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " +    position.coords.longitude + ")";

                document.getElementById("location").innerHTML = x;

     }

</script>

</body>

</html>

Explanation:

  • First checking the browser support
  • Getting current position with getCurrentPosition
  • Getting latitude and longitude values with showPosition method which is call back method of getCurrentPosition.
  • Handling Errors and Rejections: Using an Error callback function

The error Callback function serves as the second parameter for getCurrentPosition. This function is optional and is employed to manage errors and instances where the user declines to share their location during the retrieval process.

Following are the possible options for invoking the error call back function:

  • Unknown random error Occurred
  • If the user has denied for sharing location
  • Location information is not available
  • Request for location is timed-out.
  • Example

    Example
    
    function showError(error) {
    
         	switch(error.code){
    
         		case error.PERMISSION_DENIED:
    
    			alert("User denied the request for Geolocation API.");
    
    			break;
    
    		case error.POSITION_UNAVAILABLE:
    
    			alert("USer location information is unavailable.");
    
    			break;
    
    		case error.TIMEOUT:
    
    			alert("The request to get user location timed out.");
    
    			break;
    
    		case error.UNKNOWN_ERROR:
    
    			alert("An unknown error occurred.");
    
    			break;
    
    	}
    
         	}
    

    Displaying location on Google Map

Previously, we learned about displaying location using latitude and longitude coordinates; however, this method may be inadequate. Therefore, we can enhance the display by pinpointing the precise location on a Google map using this API.

The following example demonstrates how to display a location using Google Maps.

Example

Example

<!DOCTYPE html> 

<html> 

    <head> 

      <title>Geolocation API</title> 

     </head> 

    <body> 

       <h2>Find Your Location in below Map</h2> 

        <button onclick="getlocation();"> Show Position</button> 

        <div id="demo" style="width: 600px; height: 400px; margin-left: 200px;"></div> 

       

        <script src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image"> </script> 

        

        <script type="text/javascript"> 

        function getlocation(){ 

            if(navigator.geolocation){ 

                navigator.geolocation.getCurrentPosition(showPos, showErr); 

            }

            else{

                alert("Sorry! your Browser does not support Geolocation API")

            }

        } 

        //Showing Current Poistion on Google Map

        function showPos(position){ 

            latt = position.coords.latitude; 

            long = position.coords.longitude; 

            var lattlong = new google.maps.LatLng(latt, long); 

            var myOptions = { 

                center: lattlong, 

                zoom: 15, 

                mapTypeControl: true, 

                navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL} 

            } 

            var maps = new google.maps.Map(document.getElementById("demo"), myOptions); 

            var markers = 

            new google.maps.Marker({position:lattlong, map:maps, title:"You are here!"}); 

        } 



        //Handling Error and Rejection

             function showErr(error) {

              switch(error.code){

              case error.PERMISSION_DENIED:

             alert("User denied the request for Geolocation API.");

              break;

             case error.POSITION_UNAVAILABLE:

             alert("USer location information is unavailable.");

            break;

            case error.TIMEOUT:

            alert("The request to get user location timed out.");

            break;

           case error.UNKNOWN_ERROR:

            alert("An unknown error occurred.");

            break;

           }

        }        </script> 

    </body> 

</html>

For further information on the Google Maps JavaScript API, please access the provided link:

Location properties

The Geolocation API's getCurrentPosition function provides callback functions that fetch the user's location details. Upon invocation, this function yields a Position Object that encompasses various location data and defines distinct attributes. While latitude and longitude are always included, additional properties of the Position object are outlined in the table below.

Properties Description
coords.latitude It returns latitude of user location as a decimal number.
coords.longitude It returns longitude of user location as a decimal number.
coords.altitude It returns altitude in meters above the sea level (Only if available).
coords.accuracy It returns the accuracy of the user's position.
coords.altitudeAccuracy It returns the altitude accuracy of user location. (If available)
coords.heading It returns headings as degree clockwise from North. (If available)
coords.speed It returns the speed in meter per seconds. (If available).
timestamp It returns data or time of response. (If available).

Watching the current location:

To obtain precise user location as they move and receive updated positions accurately, we can utilize the watchPosition callback function.

The function includes the same three parameters as those found in getCurrentPosition.

Syntax:

Example

var id = navigator.geolocation.watchPosition(success[, error[, options]])

The function watchPosition provides an identifier that uniquely identifies the user's position. This identifier can be utilized with the clearWatch function to halt location tracking.

Syntax:

Example

navigator.geolocation.clearWatch(id);

Browser Support:

API Chrome IE Firefox Opera Safari
Geolocation 5.0 - 49.0 (http)50.0 (https) 9.0 3.5 16.0 5.0

Input Required

This code uses input(). Please provide values below: