Getting User Location with JavaScript Geolocation API
The JavaScript Geolocation API enables you to access a user’s geographical location. With this API, you can obtain the user’s current latitude and longitude coordinates, but only if they grant permission.
Project Overview: Get User Location
In this project, a button labeled “Detect your location” is displayed on the webpage. When clicked, a location prompt appears with “Allow” and “Block” options.
User Response Handling
- If the user blocks the request, the button text changes to “You denied the request”.
- If the user allows the request, the text changes to “Detecting your location”. After a few seconds, the user’s current location, including city, postal code, and country, is displayed.
- Additionally, the browser console provides more detailed location information, such as road, municipality, continent, and more.
Understanding the JavaScript Code
Before copying and pasting the code, let’s dive into the core JavaScript functionality behind this project.
Breaking Down the Code
Here’s a step-by-step explanation:
- Button Click Event: When the button is clicked, the JavaScript code is triggered.
- Geolocation API: The code uses the Geolocation API to retrieve the user’s current latitude and longitude coordinates.
- Fetch API and OpenCageData API: The coordinates are then sent to the OpenCageData server using the Fetch API, which returns detailed location information.
Important Security Note
When using APIs, remember to keep your API keys secure. Since JavaScript is a client-side language, storing your API key in the JavaScript file can expose it to users, potentially leading to misuse. Always handle API keys securely.
index.html
<!DOCTYPE html>
<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>
Styles.css
@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);
}
Script.js
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");
}