Open In App

HTML Geolocation

Improve
Improve
Like Article
Like
Save
Share
Report

The HTML Geolocation is used to get the geographical position of a user. Due to privacy concerns, this position requires user approval. Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, and restaurants, or showing locations on the map. It uses JavaScript to give latitude and longitude to the backend server.

Most browsers support Geolocation API. Geo-location API uses a global navigator object. In this article, we will know HTML Geolocation, various properties, methods & their implementation through examples.

Syntax:

var loc = navigator.geolocation

Location Properties:

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

Location Properties

Description

coords.latitude

Always returns latitude as a decimal number.

coords.accuracy

Always returns the accuracy of position.

coords.longitude

Always returns longitude as a decimal number.

coords.altitude

Returns the altitude in meters above sea level if available.

coords.altitudeAccuracy

Returns altitude accuracy of position if available.

coords.heading

Returns heading in degree clockwise from North if available

coords.speed

Returns speed in mps, if available.

timestamp

Returns date or time of response if available

Geolocation Methods:

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

Geoloaction Methods

Description

getCurrentPosition()

It fetches the current location of the user.

watchPosition()

It fetches periodic updates of the user’s current location.

clearWatch()

It cancels a watchPosition call currently in execution.

Example: This example explains returning the user’s current location using the getCurrentPosition() method.

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: 

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

Example: In this example, we simply display the current location with the help of latitude and longitude via HTML Geolocation.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <p>Displaying location using Latitude and Longitude</p>
 
    <button class="geeks" onclick="getlocation()">
        Click Me
    </button>
    <p id="demo1"></p>
 
    <script>
        let 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:

Getting the current location using 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 the above example). The PositionError object used by the error handler has two properties that let the function handle error efficiently.

  • Code
  • Message

Generated errors in geolocation: 

Error Error Description
UNKNOWN_ERRROR An unknown error
PERMISSION_DENIED The application doesn’t have permission to make use of location services
POSITION_UNAVAILABLE The location of the device is uncertain
TIMEOUT The time to fetch location information exceeded the maximum timeout interval

Example: In this example we will see the implementation of geo location in HTML document.

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

Error handling in Geolocation 

Displaying result in MAP

Displaying location on a map is a very interesting task. These services are used to provide the exact location on the map.

Example: This example describes getting the current position in Google Maps with the help of latitude and longitude via HTML Geolocation.

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

Getting the current position in Google Map

Supported Browsers:

  • Google Chrome 5
  • Microsoft Edge 12
  • Firefox 3.5
  • Opera 10.6
  • Safari 5


Last Updated : 05 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads