Get User Location in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn how to Get User Location in HTML CSS & JavaScript. In the earlier blog, I have shared how to Detect User Browser in JavaScript, and now it’s time to get user location in JavaScript using Geolocation API.

The Geolocation API of JavaScript is used to get the geographical position or location of a user.  Using this API, you will get the current latitude and longitude coordinates of the user if they allow it. In this small project (Get User Location in JavaScript), on the webpage, there is a button labeled as “Detect your location”.

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

See also  40+ CSS Transitions For Entrance & Exit Animations - transition.css

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.

Get User Location in JavaScript [Source Codes]

To create this program (Detect User Location). First, you need to create three Files: HTML, CSS & JavaScript File. After creating these files just paste the following codes into your file. You can also download the source code files of this Detect Location program from the given download button.

First, create an HTML file with the name of index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with .html extension.

<!DOCTYPE html>
<!-- Created By codeithub - www.codeithub.com -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Get User Location in JavaScript | codeithub</title>
    <link rel="stylesheet" href="https://www.codeithub.com/get-user-location-in-html-javascript/style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <button>Detect your location</button>
    <script src="script.js"></script>
  </body>
</html>

Second, create a CSS file with the name of style.css and paste the given codes in your CSS file. Remember, you’ve to create a file with .css extension.

@import url('https://fonts.googleapis.com/css2?family=Poppins:[email protected];300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: linear-gradient(#252930 50%, #5372F0 50%);
}
::selection{
  color: #fff;
  background: #5372F0;
}
button{
  border: none;
  outline: none;
  font-size: 50px;
  color: #5372F0;
  padding: 23px 44px;
  border-radius: 10px;
  cursor: pointer;
  font-weight: 500;
  background: #fff;
  box-shadow: 0 0 20px 0 rgba(0,0,0,0.1);
}

Last, create a JavaScript file with the name of script.js and paste the given codes in your JavaScript file. You’ve to create a file with .js extension and remember you have to pass your API key in the fetch URL otherwise this program won’t work. You can get this key from the official OpenCageData site for free.

const button = document.querySelector("button");

button.addEventListener("click", ()=>{
    if(navigator.geolocation){
        button.innerText = "Allow to detect location";
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }else{
        button.innerText = "Your browser not support";
    }
});

function onSuccess(position){
    button.innerText = "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} = allDetails;
        button.innerText = `${county} ${postcode}, ${country}`;
    }).catch(()=>{
        button.innerText = "Something went wrong";
    });
}

function onError(error){
    if(error.code == 1){
        button.innerText = "You denied the request";
    }else if(error.code == 2){
        button.innerText = "Location is unavailable";
    }else{
        button.innerText = "Something went wrong";
    }
    button.setAttribute("disabled", "true");
}

That’s all, now you’ve successfully created a program to Detect or Get User Location in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any error/problem, please download the source code files from the given download button. It’s free and a .zip file will be downloaded then you’ve to extract it.

See also  1kb Responsive CSS Framework - lit.css

After extracting the file, open the JavaScript file and pass your API key in the fetch URL. You can get this key from the official OpenCageData site for free. You can also use any other site API for this project. If you do so then you have to modify the JavaScript codes accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *