How to Get User Location in JavaScript (Code + Demo)

How to Get User Location in JavaScript

In this tutorial, you will learn how to get user location using javascript. I have shared many types of JavaScript projects with you before. This javascript get user location project will help to know the current location of the user.

Html, CSS, javascript, and API are used to create this project. First I designed the get user location city project using HTML and CSS. Then I activated it with the help of javascript and API.

Many times in many projects it is necessary to take the location of the user. In that case, you can use this type of design (get user location in javascript). Where the user does not need to manually add his location. Clicking on a button will automatically collect the user's current location.

Get user Location JavaScript

Here you will find live previews, source code, and tutorials. Below you will find a preview that will help you learn how it works.

See the Pen javascript get user location by Foolish Developer (@foolishdevweb) on CodePen.


As you can see above, I first designed the webpage using some CSS code. Then I created a box in which the current location address of the user can be found. Below that is a button. Clicking on that button will activate this project. 

It will basically work in the browser. Will collect all the information from the browser. The Geolocation API has been used to do this. This will show the name of your city and country.

How to get user location using Javascript

If you want to make it, follow the tutorial below. Here you will find step-by-step tutorials. If you just want the source code then follow the button below the article.

1. Basic design of user location project

The basics of this project (Get User Location in JavaScript) have been designed using the following HTML and CSS. First I designed the webpage then I created an area that will have a display and buttons.


<div class="container">

</div>




* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}

body {
height: 100vh;
background: linear-gradient(45deg, #0076ec, #42a1ff);
}

.container {
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
border-radius: 0.6em;
}

Basic design of user location project

2. Create a display to view user location

I have created a display using the code below. When you click on the button, you can see the location in the display.

The width of this box is 380px and the background color white has been used. I have also used box-shadow to enhance the beauty.


<div id="location-details">Your Location</div>


#location-details {
font-size: 1.75em;
text-align: center;
margin: 1em 0 1.7em 0;
padding: 20px;
width: 380px;
color: #021d38;
background: white;
box-shadow: 0 0.6em 2.5em rgba(0, 7, 70, 0.2);
font-weight: 500;
}


Create a display to view user location

3. Create a button to view the current location

Now I have created a button that will activate this project. The size of the button also depends on the padding: 10px 20px. The button's background color is white.


<button id="get-location">Get Location</button>


.container button {
display: block;
margin: auto;
background-color: #fcfeff;
color: #08366f;
border: none;
font-size: 1.25em;
padding: 10px 20px;
border-radius: 0.15em;
cursor: pointer;
}

Create a button to view the current location

4. Activate Get User Location using JavaScript

Now it's time to activate the Get User Location design using JavaScript. I have given here the necessary explanation of the JavaScript used here.

The constants of the buttons and the id of the display are determined using some of the following codes.
Because we can't use any HTML element directly in JavaScript.


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();
//The innerText property used to write the dynamic text on the html document.
  locationDiv.innerText = `${data.address.city}, ${data.address.country}`;
};

Get User Location using JavaScript

Javascript get user location (Source code)

Hopefully from the above tutorial, you have learned how to get the user's current location using JavaScript. But if you just want to get the source code then use the section below. 

Here you will get all the code together. For this, you create an HTML file and add the following code. Since all the code is together here, there is no need to create CSS and javascript files.

See the Pen javascript get user location by Foolish Developer (@foolishdevweb) on CodePen.


Javascript gets user location All the code of the project is in the download button below. If you have difficulty copying the above code, use the button below. 

Earlier I showed how to create a JavaScript weather application using Geolocation API. Hopefully, this article has helped you to know how to get a user's location using javascript.







Comments

Popular posts from this blog

Simple Day Night Toggle Button Using HTML and CSS

Splash Image Mask Using HTML and CSS (Free Code)

How To Limit Character In Input Field using JavaScript