Skip to content
Related Articles

Related Articles

HTML | Geolocation
  • Difficulty Level : Hard
  • Last Updated : 29 Apr, 2021

Geo-location in HTML5 is used to share the location with some web site and aware of the exact location. It is mainly used for local businesses, restaurants or showing location on the map. It uses JavaScript to give the latitude and longitude to the backend server. Most of the browsers supports Geo-location API. Geo-location API uses global navigator object which can be created as follows: 
 

var loc = navigator.geolocation

Examples: 
 

html




var loc = navigator.geolocation;
function getLoc() {
       loc.getCurrentPosition(showLoc, errHand);
}

The above function can also be written without creating a navigator object as shown below: 
 

html






function getlocation(){
        navigator.geolocation.getCurrentPosition(showLoc, errHand);
}

Displaying Location using HTML Geolocation: The following code is displaying the current location with the help of latitude and longitude via HTML Geolocation. 
 

html




<!DOCTYPE html>
<html>
    <head>
        <title>Latitude and longitude</title>
        <style>
            .gfg {
                font-size:40px;
                font-weight:bold;
                color:#009900;
                margin-left:50px;
            }
            .geeks {
                margin-left:150px;
            }
            p {
                font-size:20px;
                margin-left:20px;
            }
        </style>
    </head>
     
    <body>
        <div class = "gfg">GeeksforGeeks</div>
         
<p>Displaying location using Latitude and Longitude</p>
 
        <button class = "geeks" onclick="getlocation()">Click</button>
        <p id="demo1"></p>
 
        <script>
        var variable1 = document.getElementById("demo1");
        function getlocation(){
                navigator.geolocation.getCurrentPosition(showLoc);
        }
        function showLoc(pos){
                variable1.innerHTML = "Latitude: " + pos.coords.latitude +
                "<br>Longitude: " + pos.coords.longitude;
            }
        </script>
    </body>
</html>                   

Output: 
 

latitude and longitude

Error and Rejection Handling: It is very important to handle the errors generated in Geolocation and show a required message when an error occurs. Functions like getCurrentPosition() make use of an error handler to handle the error generated (function errHand as used in above example). The PositionError object used by error handler has two properties which let the function handle error efficiently: 
 

  • Code
  • Message

Generated errors in geolocation: 
 

ErrorError Description
UNKNOWN_ERRRORAn unknown error
PERMISSION_DENIEDThe application doesn’t have the permission to make use of location services
POSITION_UNAVAILABLEThe location of the device is uncertain
TIMEOUTTime to fetch location information exceeded the maximum timeout interval

Example: 
 

html




                        <!DOCTYPE html>
<html>
    <head>
        <title>Errors in geolocation</title>
        <style>
            .gfg {
                font-size:40px;
                font-weight:bold;
                color:#009900;
                margin-left:20px;
            }
            .geeks {
                margin-left:150px;
            }
            p {
                font-size:20px;
                margin-left:20px;
            }
        </style>
    </head>
    <body>
        <div class = "gfg">GeeksforGeeks</div>
         
<p>Error handling in geolocation</p>
 
        <button class = "geeks" onclick="getlocation()">Click</button>
        <p id="demo1"></p>
 
        <script>
        var variable1 = document.getElementById("demo1");
        function getlocation(){
                navigator.geolocation.getCurrentPosition(showLoc, errHand);
        }
        function showLoc(pos){
                variable1.innerHTML = "Latitude: " + pos.coords.latitude +
                "<br>Longitude: " + pos.coords.longitude;
            }
         
        function errHand(err) {
            switch(err.code) {
                case err.PERMISSION_DENIED:
                    variable1.innerHTML = "The application doesn't have the"+
                    "permission to make use of location services"
                    break;
                case err.POSITION_UNAVAILABLE:
                    variable1.innerHTML = "The location of the device is uncertain"
                    break;
                case err.TIMEOUT:
                    variable1.innerHTML = "The request to get user location timed out"
                    break;
                case err.UNKNOWN_ERROR:
                    variable1.innerHTML = "Time to fetch location information exceeded" +
                    "the maximum timeout interval"
                    break;
            }
        }
        </script>
    </body>
</html>                          

Output: 
 

errors in geolocation

Displaying result in MAP: Displaying location in a map is a very interesting task. This services used to provide the exact location in map.
Example:
 

html




                        <!DOCTYPE html>
<html>
    <head>
        <title>Display location in map</title>
        <style>
            .gfg {
                font-size:40px;
                font-weight:bold;
                color:#009900;
                margin-left:20px;
            }
            .geeks {
                margin-left:150px;
            }
            p {
                font-size:20px;
                margin-left:20px;
            }
        </style>
    </head>
    <body>
        <div class = "gfg">GeeksforGeeks</div>
         
<p>Display location in map</p>
 
        <button class= "geeks" type="button" onclick="getlocation();">
            Current Position</button>
        <div id="demo2" style="width: 500px; height: 500px;">
             
        </div>
             
        </script>
        <script type="text/javascript">
        function getlocation(){
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(showLoc, errHand);
            }
        }
        function showLoc(pos){
            latt = pos.coords.latitude;
            long = pos.coords.longitude;
            var lattlong = new google.maps.LatLng(latt, long);
            var OPTions = {
                center: lattlong,
                zoom: 10,
                mapTypeControl: true,
                navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL}
            }
            var mapg = new google.maps.Map(document.getElementById("demo2"), OPTions);
            var markerg =
               new google.maps.Marker({position:lattlong, map:mapg, title:"You are here!"});
        }
         
        function errHand(err) {
            switch(err.code) {
                case err.PERMISSION_DENIED:
                    result.innerHTML = "The application doesn't have the permission"  +
                               "to make use of location services"
                    break;
                case err.POSITION_UNAVAILABLE:
                    result.innerHTML = "The location of the device is uncertain"
                    break;
                case err.TIMEOUT:
                    result.innerHTML = "The request to get user location timed out"
                    break;
                case err.UNKNOWN_ERROR:
                    result.innerHTML = "Time to fetch location information exceeded"+
                      "the maximum timeout interval"
                    break;
            }
        }
        </script>
    </body>
</html>                       

Output: 
 

geolocation map

Location Properties: The following table determines properties used in getCurrentPosition() and their returning values.
 

PropertiesReturn Value
coords.latitudeAlways returns latitude as a decimal number
coords.accuracyAlways returns accuracy of position
coords.longitudeAlways returns longitude as a decimal number
coords.altitudeReturns the altitude in meters above sea level if available
coords.altitudeAccuracyReturns altitude accuracy of position if available
coords.headingReturns heading in degree clockwise from North if available
coords.speedReturns speed in mps if available
timestampReturns date or time of response if available

Geolocation Methods: The Geolocation has following methods which make it interesting and easier to work.
 

MethodDescription
getCurrentPosition()fetches the current location of the user
watchPosition()fetches periodic updates of user’s current location
clearWatch()cancels a watchPosition call currently in execution

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :