DEV Community

Cover image for How to Detect User Location using Javascript
Ashutosh Tiwari
Ashutosh Tiwari

Posted on • Originally published at incoderweb.blogspot.com

How to Detect User Location using Javascript

Hello friends, today in this blog, we will learn how to detect user location using javascript. In our previous blog, we saw how to create a Custom Card Slider Using HTML, CSS, Javascript, and Owl Carousel Plugin. Now it's time to create a user location detector. I've also shared many projects related to Javascript. So don't forget to check here.

In order to get the location of the user, we can use the Geolocation API of JavaScript which returns the geographical position of the user. Using this API we can get the current latitude and longitude coordinates of the user if they allow it. In this small project (How to Detect User Location using Javascript), on the webpage, there is a box that has an icon and button.

You May Like These:

When you click on that button, there will open a location prompt with allow and block options. If you block the request then the button text will change to “You denied the request”. If you allow the request then there will show “detecting your location”. After a few seconds, there is shown your current location including city, postal code, state code, and country.

In the console of a browser, you’ll get many other location details including road, municipality, continent, etc. If you’re feeling difficulty with what I’m saying then you can watch a demo video or full video tutorial of it.

Preview is available here.

HTML Code

<!-- ------------------ Created By InCoder ------------------ -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Detect User Location Using Javascript | InCoder</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
</head>

<body>
    <div class="card">
        <div class="icon">
            <i class="fa-solid fa-location-dot"></i>
        </div>
        <p></p>
        <div class="location"></div>
        <button class="detectBtn">Detect My Location</button>
    </div>

    <script src="script.js"></script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

CSS Code

/* ------------------ Created By InCoder ------------------ */

@import url('https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap');
* {
    margin: 0;
    padding: 0;
}

body {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #54a6d8;
}

.card {
    width: 22rem;
    margin: 1rem;
    text-align: center;
    border-radius: 10px;
    background-color: #fff;
    font-family: 'Ubuntu', sans-serif;
}

.icon {
    font-size: 6rem;
    margin-top: 1rem;
    color: #424040f0;
    margin-bottom: 1rem;
}

.location {
    font-size: 2rem;
    font-weight: bold;
    color: #424040f0;
    margin-bottom: 1rem;
}

.card p {
    font-size: 1rem;
    color: #424040f0;
    margin-bottom: 1rem;
}

.detectBtn {
    width: 15rem;
    border: none;
    color: #fff;
    outline: none;
    height: 2.5rem;
    font-size: 1rem;
    cursor: pointer;
    margin-bottom: 1rem;
    border-radius: .3rem;
    background-color: #54a6d8;
    transition: background-color .3s;
}

.detectBtn:hover {
    background-color: #424040f0;
}
Enter fullscreen mode Exit fullscreen mode

Javascript Code

let text = document.querySelector('.card p');
let locationBox = document.querySelector('.location');
let detectBtn = document.querySelector('.detectBtn');

let successFunction = (position) => {
    text.innerHTML = '';
    detectBtn.innerHTML = 'Detecting Your Location...';
    let { latitude, longitude } = position.coords;
    fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=YOUR_API_KEY`)
        .then(response => response.json()).then(response => {
            let allDetails = response.results[0].components;
            console.table(allDetails);
            let { county, postcode, country, state_code } = allDetails;
            locationBox.innerText = `${county} ${postcode} ${state_code}, ${country}`;
            detectBtn.style.display = 'none';
        }).catch(() => {
            detectBtn.innerText = "Something went wrong";
        });
}

let errorFunction = (error) => {
    if (error.code == 1) {
        text.innerHTML = 'You denied to access you location';
    } else if (error.code == 2) {
        text.innerHTML = 'Location is not available';
    } else {
        text.innerHTML = 'Something went wrong';
    }
}

detectBtn.addEventListener('click', () => {
    if (navigator.geolocation) {
        text.innerHTML = 'Allow location access to Detect your location.';
        navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
    } else {
        alert('It seems like Geolocation, which is required for this page, is not enabled in your browser.');
    }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)