Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript Geolocation API

JS Web Geolocation API

The Web Geolocation API is used to get the geographical position of a user.

What is a Geolocation API?

The Web Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it.

Geolocation is most accurate for devices with GPS, like smartphones.

The Geolocation API will only work on secure contexts such as HTTPS. If your site is hosted on a non-secure origin (such as HTTP) the requests to get the users location will no longer function.

Using the Geolocation API

The getCurrentPosition() method is used to return the user's position.

The example below returns the latitude and longitude of the user's position:

					 
        
          const x = document.getElementById("demo");
          function getLocation() {
            if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(showPosition);
            } else {
              x.innerHTML = "Geolocation is not supported by this browser.";
            }
          }

          function showPosition(position) {
            x.innerHTML = "Latitude: " + position.coords.latitude +
            "
Longitude: " + position.coords.longitude; }
Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

					 
        
          navigator.geolocation.getCurrentPosition(showPosition, showError); 

          function showError(error) {
            switch(error.code) {
              case error.PERMISSION_DENIED:
                x.innerHTML = "User denied the request for Geolocation."
                break;
              case error.POSITION_UNAVAILABLE:
                x.innerHTML = "Location information is unavailable."
                break;
              case error.TIMEOUT:
                x.innerHTML = "The request to get user location timed out."
                break;
              case error.UNKNOWN_ERROR:
                x.innerHTML = "An unknown error occurred."
                break;
            }
          }
        
      
Displaying the Result in a Map

To display the result in a map, you need access to a map service, like Google Maps.

In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):

					 
        
          function showPosition(position) {
            let latlon = position.coords.latitude + "," + position.coords.longitude;

            let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
            "+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";

            document.getElementById("mapholder").innerHTML = "<img src=""+img_url+"">";
          }
        
      
Location-specific Information

This page has demonstrated how to show a user's position on a map.

Geolocation is also very useful for location-specific information, like:

  • Up-to-date local information
  • Showing Points-of-interest near the user
  • Turn-by-turn navigation (GPS)
The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

Property Description
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)
Geolocation Object - Interesting Methods

The Geolocation object also has other interesting methods:

  • watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).
  • clearWatch() - Stops the watchPosition() method.
					 
        
          const x = document.getElementById("demo");
          function getLocation() {
            if (navigator.geolocation) {
              navigator.geolocation.watchPosition(showPosition);
            } else {
              x.innerHTML = "Geolocation is not supported by this browser.";
            }
          }
          function showPosition(position) {
            x.innerHTML = "Latitude: " + position.coords.latitude +
            "<br>Longitude: " + position.coords.longitude;
          }
        
      

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