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.
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.
Video Tutorial of Get User Location in JavaScript
In the video, you have seen the demo of this project (Get User Location in JavaScript) and how I created it using HTML CSS & JavaScript. I hope you liked this small JavaScript project and want to get source codes. But don’t worry I have given the codes or source files of this project to the bottom of this page.
You can easily copy-paste or download the code files from there. But before you go to copy-paste codes, let’s understand the main JavaScirpt codes behind creating this project. In JavaScript codes, on the button click, first, I got the current latitude and longitude coordinates of the user device using the geolocation API.
Then using fetch API, I sent a get request to the opencagedata server with passing those coordinates and got all the location details of it means I used opencagedata API to get all location details of those coordinates. Remember, you should never store your API key in the JavaScript file because it’s a client-side language. So users can easily get your key and misuse it.
You might like this:
- Custom Captcha in JavaScript
- Detect AdBlocker in JavaScript
- Detect User Browser in JavaScript
- Draggable Div Element in JavaScript
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 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, 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: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); }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.
is it possible to display location without pressing button?
Hello CodingNepal
What api key should we use? Forward or reverse or both?
Reverse geocoding because in this project we’re getting users’ locations using their lat and lang coordinations.
Hello CodingNepal
What api key should we use? Forward or reverse or both?
Hey coding nepal
I am asking the permission
for copying your codes and posting it on my own website.
Sorry, I don’t give permission for it.
Awsome, big thumbs up
Nice
Thank you