HTML5 Geolocation

To identify the geographic location of a user for a web application, the HTML Geolocation API is used. It was introduced in HTML5. The latitude and longitude coordinates of the user can be captured by JavaScript. It can then be sent to the server to display the current location on the website. To identify the location of a user the Network routing addresses such as IP addresses, RFID, WIFI and MAC addresses, or internal GPS devices are used by most of the geolocation services.

User’s privacy:

The HTML Geolocation API takes the permission of the user before getting the location to protect the privacy of the user. A notification prompt box is sent by the Geolocation API to allow or deny the permission. The location will be identified, only when the user allows it.

Geolocation object:

With navigation.geolocation object, the Geolocation API returns a Geolocation object. The location of the user is identified and based on the location of the user, a customized result is generated.

Syntax:

geo=navigator. geolocation;

Geolocation Methods:

There are three methods of Geolocation interface used by the Geolocation API:

Methods Uses
getCurrentPosition() Used to determine the device or the current location of the user and a position object is returned with data.
watchPosition() Used to get a value whenever the device location changes.
clearWatch() Used to cancel the previous watchPosition() call.

Checking for browser support:

To check the browser support for the Geolocation API, the geolocation property of navigator.geolcation object is used.

Example:

<!DOCTYPE html>  
<html>    
<body>  
<h1>Check the Current location:</h1>  
<button onclick="getlocation()">Click me</button>  
<div id="locat"></div>  
<script>  
var loc= document.getElementById("locat");  
function getlocation() {  
if(navigator.geolocation){  
alert("Geolocation API is supported")  
}  
else  
{  
alert("Sorry! Geolocation API is not supported.")  
}  
}  
</script>  
</body>  
</html>

Explanation:

In the above example, we are checking the browser support for the Geolocation API.

To get the User’s current position:

The getCurrentPosition() method of the navigator. geolocation object is used to get the current location of the user. Three parameters are thus accepted:

  • success: Used as a success callback function to get the user’s location.
  • error: Used as an error callback function to take the “Position Error” object as input.
  • options: Used to determine various options for getting the location.

Example:

<!DOCTYPE html>  
<html>    
<body>  
<h1>Check the Current location</h1>  
<button onclick="getlocation()">Click me</button>  
<div id="locat"></div>  
<script>  
var loc = document.getElementById("locat");  
function getlocation() {  
if(navigator.geolocation){  
navigator.geolocation.getCurrentPosition(showPosition)  
}  
else  
{  
alert("Sorry! Geolocation API is not supported.")  
} }  
 
function showPosition(position){  
var loc = "The current location is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " +    position.coords.longitude + ")";  
document.getElementById("locat").innerHTML = loc;  
}  
</script>  
</body>  
</html>

Explanation:

In the above example, the longitude and latitude of the user’s current location are returned. For this, the browser support is first checked. The getCurrentPosition() method is used to get the current position. The showPosition() method is used to get the latitude and longitude values.

Handling Errors and Rejections:

The error callback function is the second parameter of the getCurrentPosition method. While getting the user’s location, the errors and the user’s rejection are handled. For invoking the error call-back function, there are four possible options:

  • The occurrence of an unknown random error.
  • Denial for sharing location by the user.
  • If the location information is not available.
  • If the request for the location is timed out.

Example:

<!DOCTYPE html>  
<html>    
<body>  
<h1>Check the Current location</h1>  
<button onclick="getlocation()">Click me</button>  
<div id="locat"></div>  
<script>  
var loc = document.getElementById("locat");  
function getlocation() {  
if(navigator.geolocation){  
navigator.geolocation.getCurrentPosition(showPosition)  
}  
else  
{  
alert("Sorry! Geolocation API is not supported.")  
} }  
 
function showPosition(position){  
var loc = "The current location is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " +    position.coords.longitude + ")";  
document.getElementById("locat").innerHTML = loc;  
}  
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;  
    }  
        }  
</script>  
</body>  
</html>

Explanation:

In the above example, we are using the longitude and latitude of the user’s current location are returned. The error callback function handles any error or rejection of the user.

Displaying location on Google Maps:

Example:

<!DOCTYPE html>   
<html>      
<body>   
<h2>Check Your Location</h2>   
<button onclick="getlocation();">Check Position</button>   
<div id="loc" style="width: 400px; height: 200px; margin-left: 100px;"></div>   
 
        <script src="https://maps.google.com/maps/api/js?sensor=false"> </script>   
 
        <script type="text/javascript">   
        function getlocation(){   
            if(navigator.geolocation){   
                navigator.geolocation.getCurrentPosition(showPos, showErr);   
            }  
            else{  
                alert("Sorry! Geolocation API is not supported.")  
            }  
        }   
 
        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("loc"), myOptions);   
            var markers =   
            new google.maps.Marker({position:lattlong, map:maps, title:"I am here!"});   
        }   
        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>

Explanation:

In the above example, we are displaying the location on Google Maps.

Location properties:

The callback methods are returned by the getCurrentPosition() method of the Geolocation API to retrieve the location information of the visitor. A Position object containing the location information is returned by the callback method. It is used to define different properties. The latitude and longitude properties are returned always.

Other properties of the Position object:

Properties Uses
coords.latitude Used to get the latitude of the location of the user as a decimal number.
coords.longitude Used to get the longitude of the location of the user as a decimal number.
coords.altitude Used to get the altitude in meters above the sea level if available.
coords.accuracy Used to get the accuracy of the position of the user if available.
coords.altitudeAccuracy Used to get the altitude accuracy of the location of the user if available.
coords.heading Used to get the headings as degree clockwise from North if available.
coords.speed Used to get the speed in meters per second if available.
timestamp Used to get the data or time of response if available.

Watching the current location:

The watchPosition() callback function is used to know the location of the user while the user is moving. It provides an accurate location at every changed position. All three parameters of the getCurrentPosition() are present in this function. The watchPosition() method returns an ID. This ID is used to uniquely identify the position of the user.

Syntax:

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

The ID returned by the watchPosition() method can be used with the clearWatch() method to stop watching the location.

Syntax:

navigator.geolocation.clearWatch(id);

Supporting Browser:

Chrome, IE, Firefox, Opera, and Safari.

Please follow and like us:
Content Protection by DMCA.com