• Post category:JavaScript
  • Reading time:4 mins read

Today we’ll show you how to get current geolocation in JavaScript using Geolocation API. 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 location 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

<!DOCTYPE html>
<html>

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

<body>

  <h3>Get current Geolocation in JavaScript - <a href="https://www.codepremix.com" target="_blank" rel="noopener noreferrer">Code Premix</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>

</body>

</html>

Run the above file and check in the output in the browser console.

Leave a Reply