How to Detect User Location using Javascript
Tags: javascript, html, css, incoder
Published: 2022-03-28 17:11:18

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](https://incoderweb.blogspot.com/search/label/Javascript).

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:

- [Responsive Sidebar Menu Design](https://incoderweb.blogspot.com/2022/02/responsive-sidebar-menu-design-using.html)
- [Custom Video Player Design](https://incoderweb.blogspot.com/2022/03/custom-video-player-design.html)
- [Custom Context or Right Click Menu Design](https://incoderweb.blogspot.com/2022/02/custom-context-or-right-click-menu.html)
- [Cookie Consent Box Design](https://incoderweb.blogspot.com/2022/01/cookie-consent-box-using-html-css-and.html)

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](https://incoderweb.blogspot.com/2022/03/how-to-detect-user-location.html).

##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>
```

##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;
}
```

##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.');
    }
});
```