How to Get User Location in HTML CSS & JavaScript
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.
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, paste the following codes into your index.html file.
<!-- Created By CodingNepal - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
<title>Get User Location in JavaScript | CodingNepal</title>
<link rel="stylesheet" href="style.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<button>Detect your location</button>
<script src="script.js"></script>
<!DOCTYPE html>
<!-- Created By CodingNepal - www.codingnepalweb.com -->
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Get User Location in JavaScript | CodingNepal</title>
<link rel="stylesheet" href="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, paste the following codes into your style.css file
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
font-family: 'Poppins', sans-serif;
background: linear-gradient(#252930 50%, #5372F0 50%);
box-shadow: 0 0 20px 0 rgba(0,0,0,0.1);
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;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);
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}`;
button.innerText = "Something went wrong";
button.innerText = "You denied the request";
}else if(error.code == 2){
button.innerText = "Location is unavailable";
button.innerText = "Something went wrong";
button.setAttribute("disabled", "true");
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.
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.