Clue Mediator

Get current Geolocation using JavaScript

📅September 28, 2020

Today we’ll show you how to get current geolocation using JavaScript. In this small article, we will use JavaScript's Geolocation API to get the latitude and longitude of the visitor’s position.

Let’s create a sample example to get the geolocation using JavaScript. In this example, we will show you the location information in the browser console.

Example to get current geolocation

Here we will use the `Navigator.geolocation` property to get the Geolocation object. Using this property, we can get the location access of the device to read the latitude and longitude.

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(position => {
    const lat = position.coords.latitude;
    const long = position.coords.longitude;
    console.log('Latitude: ', lat);
    console.log('Longitude: ', long);
  }, error => {
    console.log('Need access to get location.');
  });
}

When executing code in the browser, it will ask permission to allow access to the location.

Output

Let’s use the above code in the sample HTML page and check the logs of the browser console.

index.html





  <title>Get current Geolocation - Clue Mediator</title>
  <style>
    body {
      font-family: Arial, Helvetica, sans-serif;
    }
  </style>




  <h3>Get current Geolocation using JavaScript - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue
      Mediator</a></h3>

  <b>Turn on Allow apps to access your location.</b>

  <script>
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        const lat = position.coords.latitude;
        const long = position.coords.longitude;
        console.log('Latitude: ', lat);
        console.log('Longitude: ', long);
      }, error => {
        console.log('Need access to get location.');
      });
    }
  </script>

Run the above file and check in the browser.

Output - Get current Geolocation using JavaScript - Clue Mediator

Output - Get current Geolocation using JavaScript - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!