How to get user location in the browser using JavaScript?

You can use the Geolocation API in JavaScript to retrieve the user’s location in a web browser. Here’s a basic example of how to do it:

// Check if geolocation is available in the browser
if ("geolocation" in navigator) {
    // Get the user's current location
    navigator.geolocation.getCurrentPosition(function(position) {
        // The user's latitude and longitude are in position.coords.latitude and position.coords.longitude
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;

        console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
    }, function(error) {
        // Handle errors, if any
        switch (error.code) {
            case error.PERMISSION_DENIED:
                console.error("User denied the request for geolocation.");
                break;
            case error.POSITION_UNAVAILABLE:
                console.error("Location information is unavailable.");
                break;
            case error.TIMEOUT:
                console.error("The request to get user location timed out.");
                break;
            case error.UNKNOWN_ERROR:
                console.error("An unknown error occurred.");
                break;
        }
    });
} else {
    console.error("Geolocation is not available in this browser.");
}

In this code:

  1. We first check if the navigator object has the geolocation property, ensuring that geolocation is supported in the browser.
  2. If geolocation is supported, we call navigator.geolocation.getCurrentPosition() to request the user's current position. This function takes two callbacks as arguments: one for success and one for error handling.

Website