Get user location from browser using JavaScript

In this short article, we will learn how to get users' current location of our website.

If you are building any location-based website like food delivery apps etc, it becomes important to get the location of the user to show them more accurate results on the website.

How do we get the user location from the browser?

The answer is using Geolocation Web API. Using this Web API, we can get the location i.e the longitude and the latitude coordinates of the users who visit our website or app

What is Geolocation Web API ?

The geolocation API allows a user to provide their location coordinates to the web application if they desire.

When a user visits the website for the first time, the browser will prompt the user to allow location access to the site. The user can allow or block the API from accessing the location.

How can we access the geolocation API using JavaScript?

To access the Web API we have to use the navigator property of the window object inside the browser.

The navigator property contains another property called the geolocation which is also an object with its own properties.

And the Geolocation API is available through this navigator.geolocation object.

Get user location from browser JavaScript

Now let's code to get the location of users

if('geolocation' in navigator){
    //geolocation is available
} else {
    // geolocation not available

Even though most modern browsers support geolocation API it's better to check if the navigator contains the geolocation object using if statement.

Now if the browser supports it, then we can request the users to provide us the user location from the Geolocation API.


Get user location from browser using JavaScript

The user can allow or block the API to get their current location.

Inside the if statement we will use the getCurrentPosition() function to get the coordinates and other location data.

if('geolocation' in navigator){
    window.navigator.geolocation.getCurrentPosition(console.log, console.log);

Output on console is:

access user location from browser JavaScript

Now to get the current user's longitude and latitude we have to code like this

if ('geolocation' in navigator) {
   navigator.geolocation.getCurrentPosition((position) => {
   getCoordinates(position.coords.latitude, position.coords.longitude);

function getCoordinates(lat, long){
  console.log(lat, long)

Here in the above code, when a user clicks allow the getCurrentPosition() function runs and this will cause the getCoordinates() function to execute when the location is obtained from the user's browser.

So, this is the simple way you can use the Geolocation API to get user location from a browser using JavaScript.

💾 Recommended Articles