create account

How to get user location using Javascript geolocation. by tykee

View this thread on: hive.blogpeakd.comecency.com
· @tykee ·
$5.58
How to get user location using Javascript geolocation.
![](https://images.ecency.com/DQmPeHSrvkciLQg8pF3nZT7FHHGGoeZqhws6KDGYMAW3xgJ/dw_1.png)




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)
}`

![](https://images.ecency.com/DQmW6X9sPo849tx3fQ1GncUMnWVz5XqtdYtghkRRdEfndsk/95b4a035_bd35_4e94_a273_228f2168343f_4_5005_c.jpeg)



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](https://images.hive.blog/DQmbaXWUkhbUsnSqUyQmNCTfdxEtRGoxtw7u5uFzPTCFPKH/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. 

<sub>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</sub>

Posted with [STEMGeeks](https://stemgeeks.net)
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 203 others
properties (23)
authortykee
permlinkhow-to-get-user-location-using-javascript-geolocation
categoryhive-163521
json_metadata{"tags":["neoxian","proofofbrain","vyb","cent","ctp","hive-engine","location","hive","stem"],"image":["https://images.ecency.com/DQmPeHSrvkciLQg8pF3nZT7FHHGGoeZqhws6KDGYMAW3xgJ/dw_1.png","https://images.ecency.com/DQmW6X9sPo849tx3fQ1GncUMnWVz5XqtdYtghkRRdEfndsk/95b4a035_bd35_4e94_a273_228f2168343f_4_5005_c.jpeg","https://images.hive.blog/DQmbaXWUkhbUsnSqUyQmNCTfdxEtRGoxtw7u5uFzPTCFPKH/AB99307A-8F0B-42B0-95B0-26EB6755EF64.jpeg"],"app":"stemgeeks/0.1","format":"markdown","canonical_url":"https://stemgeeks.net/@tykee/how-to-get-user-location-using-javascript-geolocation"}
created2023-05-21 19:30:03
last_update2023-05-21 19:30:03
depth0
children9
last_payout2023-05-28 19:30:03
cashout_time1969-12-31 23:59:59
total_payout_value2.810 HBD
curator_payout_value2.766 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length3,644
author_reputation232,935,449,922,164
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,704,147
net_rshares11,970,423,117,731
author_curate_reward""
vote details (267)
@discovery-it ·
<div class="pull-left">https://cdn.steemitimages.com/DQmTAn3c753LR7bHCLPo96g9UvRMaPFwaMYn8VQZa85xczC/discovery_logo_colore%20-%20Copia.png</div><br> This post was shared and voted inside the discord by the curators team of <a href="https://discord.gg/cMMp943"> discovery-it</a> <br>Join our <a href = "https://hive.blog/trending/hive-193212"> Community</a> and follow our <a href = "https://hive.vote/dash.php?i=1&trail=discovery-it">Curation Trail</a><br>Discovery-it is also a Witness, vote for us <a href = "https://hivesigner.com/sign/account-witness-vote?witness=discovery-it&approve=true"> here</a>  <br>Delegate to us for passive income. Check our <a href = "https://hive.blog/hive-193212/@discovery-it/delegations-program-80-fee-back"> 80% fee-back Program</a> <hr>
properties (22)
authordiscovery-it
permlinkre-tykee-50q5t4ibud
categoryhive-163521
json_metadata"{"app": "beem/0.24.26"}"
created2023-05-21 21:11:03
last_update2023-05-21 21:11:03
depth1
children0
last_payout2023-05-28 21:11:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length773
author_reputation47,706,240,393,884
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,708,171
net_rshares0
@enforcer48 ·
Cool and unsettling at the same time. I share similar sentiments with other self-conscious individuals. 

!discovery 31
properties (22)
authorenforcer48
permlinkre-tykee-rv11i6
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2023.5.1"}
created2023-05-21 21:10:54
last_update2023-05-21 21:10:54
depth1
children1
last_payout2023-05-28 21:10:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length119
author_reputation404,954,516,818,944
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,708,166
net_rshares0
@tykee ·
$0.08
Absolutely, we all need to be careful. Thanks for your comment.
πŸ‘  ,
properties (23)
authortykee
permlinkrv14vs
categoryhive-163521
json_metadata{"app":"hiveblog/0.1"}
created2023-05-21 22:23:57
last_update2023-05-21 22:23:57
depth2
children0
last_payout2023-05-28 22:23:57
cashout_time1969-12-31 23:59:59
total_payout_value0.038 HBD
curator_payout_value0.038 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length63
author_reputation232,935,449,922,164
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,710,819
net_rshares163,302,334,567
author_curate_reward""
vote details (2)
@mbfreddys ·
Amazing πŸ‘Œ
πŸ‘  , , ,
properties (23)
authormbfreddys
permlinkre-tykee-2023522t18642632z
categoryhive-163521
json_metadata{"tags":["neoxian","proofofbrain","vyb","cent","ctp","hive-engine","location","hive","stem"],"app":"ecency/3.0.39-mobile","format":"markdown+html"}
created2023-05-22 22:07:18
last_update2023-05-22 22:07:18
depth1
children1
last_payout2023-05-29 22:07:18
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9
author_reputation2,454,083,086,214
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,741,058
net_rshares125,527,674
author_curate_reward""
vote details (4)
@tykee ·
properties (23)
authortykee
permlinkre-mbfreddys-2023522t2382332z
categoryhive-163521
json_metadata{"tags":["hive-163521","neoxian","proofofbrain","vyb","cent","ctp","hive-engine","location","hive","stem"],"app":"ecency/3.0.39-mobile","format":"markdown+html"}
created2023-05-22 22:08:24
last_update2023-05-22 22:08:24
depth2
children0
last_payout2023-05-29 22:08:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9
author_reputation232,935,449,922,164
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,741,077
net_rshares125,318,556
author_curate_reward""
vote details (4)
@stemsocial ·
re-tykee-how-to-get-user-location-using-javascript-geolocation-20230522t032353299z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> 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.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-tykee-how-to-get-user-location-using-javascript-geolocation-20230522t032353299z
categoryhive-163521
json_metadata{"app":"STEMsocial"}
created2023-05-22 03:23:54
last_update2023-05-22 03:23:54
depth1
children0
last_payout2023-05-29 03:23:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length565
author_reputation22,463,635,119,853
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,719,318
net_rshares0
@yintercept ·
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
πŸ‘  
properties (23)
authoryintercept
permlinkre-tykee-rv0y3d
categoryhive-163521
json_metadata{"tags":["hive-163521"],"app":"peakd/2023.5.1"}
created2023-05-21 19:57:15
last_update2023-05-21 19:57:15
depth1
children2
last_payout2023-05-28 19:57:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,305
author_reputation23,962,343,431,134
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,705,193
net_rshares0
author_curate_reward""
vote details (1)
@tykee ·
$0.04
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.
πŸ‘  ,
properties (23)
authortykee
permlinkrv10wp
categoryhive-163521
json_metadata{"app":"hiveblog/0.1"}
created2023-05-21 20:58:06
last_update2023-05-21 20:58:06
depth2
children0
last_payout2023-05-28 20:58:06
cashout_time1969-12-31 23:59:59
total_payout_value0.018 HBD
curator_payout_value0.018 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length167
author_reputation232,935,449,922,164
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,707,689
net_rshares79,680,674,082
author_curate_reward""
vote details (2)
@wine.bot ·
<center>
<sup>Congratulations, @yintercept You Successfully Shared <b>0.100</b> <b>WINEX</b> With @tykee.</sup>
<sup>You Earned <b>0.100</b> <b>WINEX</b> As Curation Reward.</sup>
<sup>You Utilized <b>1/1</b> Successful Calls.</sup>

<img src="https://images.hive.blog/DQmSWfbie9MTC172sENiA16bsMaz1ofT6AAyTo1ishasrcX/winexcomment.png" alt="wine_logo">

---
<sup>Contact Us : [WINEX Token Discord Channel](https://discord.gg/rS3KzjJDCx)</sup>
<sup>[WINEX Current Market Price](https://hive-engine.com/?p=market&t=WINEX) : <b>0.094</b></sup>
---
<sup>Swap Your <b>Hive <=> Swap.Hive</b> With Industry <b>Lowest Fee (0.1%)</b> : [Click This Link](https://swaphive.github.io/swap/)</sup>
<sup>[Read Latest Updates](https://peakd.com/@hiveupme/posts) Or [Contact Us](https://discord.gg/rS3KzjJDCx)</sup>
</center>
properties (22)
authorwine.bot
permlink20230521t195737190z
categoryhive-163521
json_metadata{"tags":["wine","token","winebot"],"app":"ecency/3.0.31-vision","format":"markdown+html"}
created2023-05-21 19:57:36
last_update2023-05-21 19:57:36
depth2
children0
last_payout2023-05-28 19:57:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length823
author_reputation2,782,560,914,577
root_title"How to get user location using Javascript geolocation."
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id123,705,219
net_rshares0