How to get user location using Javascript geolocation.

avatar

This is another part of my front-end series. Today, I will explain how to get users location with JavaScript.

Without further ado, let’s push.

This is the html file.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="style.css">
   <title>Document</title>
</head>
<body>
   <div class="container">
       <button class="findme">FIND ME</button>
       <h2 class="myLocation"></h2>
   </div>
   <script src="main.js"></script>
</body>
</html>

This is the css

.container {
display: flex;
justify-content: space-evenly;
align-items: center;
margin-top: 25%;
background: rgb(97, 94, 94);
height: 200px;
}


.myLocation {
   color: #fff;
}


 button {
   background-color: #4CAF50;
   border: none;
   color: white;
   padding: 15px 52px;
   text-align: center;
   text-decoration: none;
   /* display: inline-block; */
   font-size: 16px;
 }

This is the Javascript

navigator.geolocation.getCurrentPosition(success, error)
and the function

const success = (position) => { console.log(position) }

Will log the geolocationposition and geolocationcoordinate in the console and the error function will return the message specified in the code if the position is not allowed on the computer.

After that, I fetched out the latitude and longitude and used a geolocation API to concatenate the latitude and longitude in the API.

Finally, I fetched my location from the API and it will return all of these:

city: ""
continent: ""
continentCode: ""
countryCode: ""
countryName: ""
latitude:
locality: ""
localityInfo: {LikelyLand: true, administrative: Array(4), informative: Array(3)}
localityLanguageRequested: "en"
longitude:
lookupSource: ""
plusCode: ""
postcode: ""
principalSubdivision: ""
principalSubdivisionCode: ""

Then I fetched the continent on the website, you can fetch any another you wish using the same method. The JavaScript code below explains all.

AB99307A-8F0B-42B0-95B0-26EB6755EF64.jpeg

const findMe = () => {
   const myLocation = document.querySelector('.myLocation');


   const success = (position) => {
       console.log(position)
       const latitude = position.coords.latitude;
       const longitude = position.coords.longitude;
       const geolocationApi = `https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${latitude}&longitude=${longitude}&localityLanguage=en`


       fetch(geolocationApi)
       .then(res => res.json())
       .then(data => {
           myLocation.textContent = data.continent
       })
   }


   const error = () => {
       myLocation.textContent = "Location not available"
   }
   navigator.geolocation.getCurrentPosition(success, error)
};


document.querySelector('.findme').addEventListener('click', findMe)

You can copy the code, test it in your code editor, and play with it based on your wants.

I hope you find this useful

Thank you for reading.

Michael B, A.K.A Tykee, I am a software developer, writer and blockchain enthusiast. I write about finance, programming, tech and lifestyle. My contents are my opinions

Posted with STEMGeeks



0
0
0.000
9 comments
avatar

Geolocation technology is really fun. I've implemented it on a few sites.

One can do fun things with geolocation like draw maps of one's activities.

Fun things come with dangers. So, I thought I would drop my pet peeves about geolocation.

The things I dislike:

IMHO: The best geolocation implementations put the code in a button, like you are doing. This way the user has to engage in an affirmative action to get the geolocation.

Many web sites put the geolocation in the header and call the program when loading a page.

There is nothing more annoying that an web site that demands one's location on entering the site.

I usually just leave sites that prompt for my location on page load.

There are only a few sites that I would trust with my current location.

The Temptation to Publish Real Time Locations

There is a huge temptation to publish the geolocation of users. One should always implement a substantive time delay when publishing geolocations.

For example, a person who is on vacation broadcasts to the world that their house is empty when publishing a photo with a geolocation.

Things like geolocation and email address are private information and need to be treated as such.

Great Article

I love geolocation apps. I hope you didn't mind my voicing my pet peeves.

!WINE

0
0
0.000
avatar

This is a great comment and I agree with them. There are dangers that come with location and it should be used right. Thank you for the gift and the valuable comment.

0
0
0.000
avatar

Cool and unsettling at the same time. I share similar sentiments with other self-conscious individuals.

!discovery 31

0
0
0.000
avatar

Absolutely, we all need to be careful. Thanks for your comment.

0
0
0.000
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000