In this article we will learn how we to fetch users current location or how to get geolocation in javascript, So first we need to learn about the browser navigators or what is window.navigator, So when we use some browser on desktop, mobile, laptop etc, there are some state what user need to enable, so browser can access some user specific information and provide to website on the browser in other terms window.navigator can be defined as below
Browser navigator Api (window.navigator)
The Navigator
 interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.
so for example if user enables bluethoot then in navigator api Navigator.bluetooth
will return Bluetooth
 object for the current document, providing access to Web Bluetooth API functionality, javascript get gps location
Same way we have navigator.geolocation which provides the current latitude and longitude of the user from where he or she is browsing the website and for this we need to enables the locations setting from browser once user enables the location only then we are able to fetch current latitude and longitude. So below is the options showed in image by which user can enable the location on the website.
javascript geolocation ask permission, Once you Allow the website to enable user locations, the we need to fetch the latitude and longitude once we able to get these values then we will pass it to google geolocation API, So let learn how we can fetch the latitude and latitude navigator.geolocation javascript example is below
navigator.geolocation.getCurrentPosition(userPosition, error);
in above code we have a navigator object and inside the geolocation.getCurrentPosition() function which will return parameters, in first parameters we have the position as a result and in second we have error if there is some restrictions in getting the latitude and longitude (if location is not allowed by user or JavaScript is not working on browser), in above code userPosition is a callback function which we can execute and get the user location city etc. and the other parameter is error is we face any error in getting the position of the user.
Geocoding service (Google Maps Geocoding API)
Now we will use google geocoding service to get the user location, for that we need the google api key which you can get from google JavaScript API, below is the url from where you can get the API keys
https://developers.google.com/maps/documentation/geocoding/overview
Now lets try to extend the geolocation code to get the user location
function getUserLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, error);
} else {
document.getElementById("location").innerHTML = "Geolocation is not supported by this browser.";
}
}
function userPosition(position) {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
const apiKey = 'YOUR_GOOGLE_MAPS_API_KEY'; // Replace with your API key
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${apiKey}`;
fetch(url)
.then(response => response.json())
.then(data => {
const addressComponents = data.results[0].address_components;
let city = '';
let state = '';
addressComponents.forEach(component => {
if (component.types.includes('locality')) {
city = component.long_name;
}
if (component.types.includes('administrative_area_level_1')) {
state = component.short_name;
}
});
document.getElementById("location").innerHTML = `City: ${city}, State: ${state}`;
})
.catch(error => {
document.getElementById("location").innerHTML = "Error: " + error;
});
}
function error(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
document.getElementById("location").innerHTML = "User denied the Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
document.getElementById("location").innerHTML = "Location is unavailable.";
break;
case error.TIMEOUT:
document.getElementById("location").innerHTML = "The request timed out.";
break;
case error.UNKNOWN_ERROR:
document.getElementById("location").innerHTML = "An unknown error occurred.";
break;
}
}
Above code we have passed the user current latitude and longitude we get from navigator.geolocation.getCurrentPosition is passed to function userPosition, we stored potitions in lat, lon variable in function userPosition store and api url where we pass lat and lon variable https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${apiKey}
var apiKey you need to get is from google geocoding api after than by using fetch api method we hit the api url and if everything is correct then as a result we will get the current location city , state, pin code address of the user using browser