Loading Please Wait...

Logo Lynxsia IT Solutions

HTML Geolocation API

HTML Geolocation

HTML Geolocation API is used to get graphical location of the user.

Location is most accurate in GPS like device such as mobile phones.

As the location of the user may compromise the privacy, so user must approve it otherwise it will not work.

Get User Location

To get user location, use getCurrentPosition() method of the navigator.geolocation object

The navigator object is used to get browser information such as appName, userAgent, etc. navigator.geolocation object consist of only location based information such as latitude, longitude, etc.

Let's see with some example
					 
        
          <button type="button" onClick="getLocation()">Get Location</button>
          <script>
            function getLocation() {
              if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
              } else {
                alert('Geolocation is not supported by this browser.');
              }
            }
            function successCallback(position) {
              alert('Location fetched successfully.');
              alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
              console.log(position);
            }
            function errorCallback(error) {
              alert('Failed to get location.');
              console.log(error);
            }
          </script>
        
      
Example Explained

The navigator.geolocation check if geolocation is supported by browser or not.

The getCurrentPosition() method try to get the location. If location fetched then successCallback() method called otherwise errorCallback() method called.

How It Works
Click On button

When you click on "Get Location" button, a popup is displayed asking for user permissions.

get location permission popup
Deny

When you click on "Block" or cross(x), the permission is denied and a log message is displayed in console. Inspect page and click on console tab.

error callback
Allow

When you click on "Allow", longitude and latitude is displaced via alert and a log message is displayed on console. Inspect page and click on console tab.

success callback
getCurrentPosition() Data

The getCurrentPosition() method provides the following data.

  • coords

    Co-ordinates specific information

    • coords.accuracy = The accuracy of position
    • coords.altitude = The altitude in meters above the mean sea level
    • coords.altitudeAccuracy = The altitude accuracy of position
    • coords.heading = The heading as degrees clockwise from North
    • coords.latitude = The latitude as a decimal number
    • coords.longitude = The longitude as a decimal number
    • coords.speed = The speed in meters per second
  • timestamp

    The date/time when location is fetched.

Continue Fetching Location

The watchPosition() method continue fetch current (updated) location of the user as user moves.

The clearWatch() method stop watchPosition() method.

Let's see with some example
					 
        
          <button type="button" onClick="getLocation()">Get Location</button>
          <script>
            function getLocation() {
              if (navigator.geolocation) {
                navigator.geolocation.watchPosition(successCallback, errorCallback);
              } else {
                alert('Geolocation is not supported by this browser.');
              }
            }
            function successCallback(position) {
              alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
            }
            function errorCallback(error) {
              alert('Failed to get location.');
            }
          </script>
        
      
Passing Optional Parameters

The optional parameter helps in fetching more accurate location.

Let's see with some example
					 
        
          <button type="button" onClick="getLocation()">Get Location</button>
          <script>
            const options = {
              enableHighAccuracy: true,
              timeout: 10000,
            };
            function getLocation() {
              if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
              } else {
                alert('Geolocation is not supported by this browser.');
              }
            }
            function successCallback(position) {
              alert("Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
            }
            function errorCallback(error) {
              alert('Failed to get location.');
            }
          </script>
        
      

How you feel about this blog:

Share this blog on:

Report Us

If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com

Contact Us
Ads
Logo
Lynxsia IT Solutions

We are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved