HTML5 Geolocation

To get the location of a user in HTML5, we use geolocation API.Using the HTML5 Geolocation API ,you can request user to share their location. It uses JavaScript to get the latitude and longitude .Most of the browsers support Geolocation API.

Syntax:-

var location = navigator.geolocation;

Geolocation Method:- Geolocation object provides the following methods

1. getCurrentPosition() :- This method retrieves the current geographic location of user.

2. watchPosition() :- This method retrieves period updates about the current geographic.

3. clearwatch() :-This method cancels an ongoing watchPosition call.

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 can’t provides the value, the value of property is set to null.

Property Type Description
coords object Specifies the geographic location of the device.
coords.latitude number Specifies the latitude estimate in decimal.
coords.longitude number Specifies the longitude estimate in decimal.
coords.altitude number (Optional)Specifies the altitude estimate in meter.
coords.accuracy number (Optional)Specifies the accuracy of latitude and longitude estimate in meter.
coords.altitudeAccuracy number (Optional)Specifies the accuracy of the altitude estimate in meters.
coords.heading number (Optional)Specifies the devices’s current direction of movement in degrees counting clockwise.
coords.speed number (Optional)Specifies the devices current ground speed in meters per second
timestamp date Specifies the time when the location information was retrieved and the Position object created.

Example: This example given below  return the user’s current location using the getCurrentPosition() method.

<!DOCTYPE html>
<html>
<head>
    <title>Latitude and longitude</title>
</head>
<body>
    <center>
        <h1 class="gfg" style="color:green;">
            Your Location Longitude and Latitude
        </h1>
        <h2 id="Location"></h2>
    </center>
    
    <script>
        var Location = document.getElementById("Location");
        navigator.geolocation.getCurrentPosition(showLocation);

        function showLocation(position)
       {
            Location.innerHTML =
            "Latitude: " + position.coords.latitude +
            "<br>Longitude: " + position.coords.longitude;
        }
    </script>
</body>
</html>