How To Get User Location Using JavaScript (Free Code)

Do you want to know User Location by JavaScript? From this tutorial you will know how to know User Location only with the help of javascript.

Sometimes in many projects we need to know the user’s location. In that case, you can know the user’s location very easily with the help of this project(javascript get user location city).

How To Get User Location Using JavaScript

Earlier I have shared various JavaScript tutorials. Hope you like this tutorial as much as those designs.

Here I have used API to get user location which will collect location from user device and display it in web page. Here basically I have arranged to show country and town.

Get User Location JavaScript

There are many projects in which we need to know the user’s location like registration form, download button etc. In that case this project will help you a lot.

From this tutorial you will get a basic concept of how to find user location using javascript. Here I have used html css and basic javascript.

See the Pen Get User Location Using JavaScript by Ground Tutorial (@groundtutorial) on CodePen.

Hope you get to know how it works from the preview above. As you can see this HTML User Location project is very simple.

I have created a box within the webpage. Which contains some text, a button and an image. When you click on the button, a small box will show the user’s location.

How To Get User Location with JavaScript

To create this project(get user location from browser javascript) I first used basic html. Then I implemented the Detect User Location project using css. Finally, I made this project functional by JavaScript and api.

If you want to know how I made this project then follow the tutorial below. Use the download button below the article for the source code.

1. Basic Structure of User Location Project

First I created a basic structure using the following html and css code. Basically I have created a box on the webpage.

				
					<div class="container">

</div>
				
			
				
					* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  height: 100vh;
  background: #132442;
}
				
			

I have used the following css to design the key box. Here I have used box width: 80vw, min-width: 480px and background-color: #ffffff.

				
					.container {
  width: 80vw;
  min-width: 480px;
  max-width: 37.5em;
  background-color: #ffffff;
  padding: 3em 1.8em;
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
  border-radius: 0.6em;
  box-shadow: 0 0.6em 2.5em rgba(0, 7, 70, 0.2);
}
				
			
Basic Structure of User Location Project

2. Add an image to the project

Now I used an image to add some beauty to this project. Added images using html and designed with css.

				
					<img width="200" height="200" decoding="async" src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20200%20200'%3E%3C/svg%3E" data-lazy-src="http://groundtutorial.com/wp-content/uploads/2022/12/location.svg" /><noscript><img width="200" height="200" decoding="async" src="http://groundtutorial.com/wp-content/uploads/2022/12/location.svg" /></noscript>
				
			
				
					.container img {
  width: 6.25em;
  display: block;
  margin: auto;
}
				
			
Add an image to the project

3. Now added basic text

Now I have added a basic text by following code. This text is not important but is used only to explain to the user how this works. Added text with simple html and then designed with css.

				
					<div id="location-details">Click on the 'Get Location' Button</div>
				
			
				
					#location-details {
  font-size: 1.75em;
  text-align: center;
  margin: 1em 0 1.7em 0;
  color: #021d38;
  font-weight: 500;
}
				
			
Now added basic text

4. Create a button to know user location

Now I have created a button in this design(How To Get User Location Using JavaScript). This button will activate the project.

When the user clicks on this button, JavaScript will be executed and all uniforms will be visible in a preview section below.

				
					<button id="get-location">Get Location</button>
				
			
				
					.container button {
  display: block;
  margin: auto;
  background-color: #1d538a;
  color: #ffffff;
  border: none;
  font-size: 1.25em;
  padding: 1em 2.5em;
  border-radius: 0.25em;
  cursor: pointer;
}
				
			
Create a button to know user location

5. Using JavaScript to know user location

The above html css is not very difficult to understand. But now the user’s location must be collected by javascript and viewed in the project.

Here I have tried to explain to you what code is used and why with possible explanations and comments with each line.

				
					let locationButton = document.getElementById("get-location");
let locationDiv = document.getElementById("location-details");

locationButton.addEventListener("click", () => {
  //Geolocation APU is used to get geographical position of a user and is available inside the navigator object
  if (navigator.geolocation) {
    //returns position(latitude and longitude) or error
    navigator.geolocation.getCurrentPosition(showLocation, checkError);
  } else {
    //For old browser i.e IE
    locationDiv.innerText = "The browser does not support geolocation";
  }
});

//Error Checks
const checkError = (error) => {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      locationDiv.innerText = "Please allow access to location";
      break;
    case error.POSITION_UNAVAILABLE:
      //usually fired for firefox
      locationDiv.innerText = "Location Information unavailable";
      break;
    case error.TIMEOUT:
      locationDiv.innerText = "The request to get user location timed out";
  }
};

const showLocation = async (position) => {
  //We user the NOminatim API for getting actual addres from latitude and longitude
  let response = await fetch(
    `https://nominatim.openstreetmap.org/reverse?lat=${position.coords.latitude}&lon=${position.coords.longitude}&format=json`
  );
  //store response object
  let data = await response.json();
  locationDiv.innerText = `${data.address.city}, ${data.address.country}`;
};
				
			
How To Get User Location Using JavaScript

Do comment how you like this tutorial(get user location without permission) and I have shared many more tutorials like this. To learn more about JavaScript, see this tutorial.

If you want the complete source code of this project, you can use the download button below the article.

As you know from this tutorial knowing the user location is very difficult with noi javascript. Here I have provided the basic idea how to know user’s location by api.

It is possible to know the user’s location without permission, but the user has to do some action. For example, when the user clicks on the button, the location will be known.

As you can see in this project here I have managed to know the user’s city and country. So you will know from this tutorial how to get user location city by Javascript.

If you want to know user’s location by browser with user’s permission then this tutorial will be best for you. This tutorial created by freecodecamp.org will help you how to do this.

Leave a Comment