How to get user’s location with React JS
Tags: react, webdev, javascript, tutorial
Published: 2020-11-25 17:48:59

#Hi there,
How are you guys? I’m Web Developer, I want to share few interesting learnings that I do every day, and I thought an Article is a good way to do that, So let’s directly jump to the point without making you bore. 😜

> BTW…This is my first article! 🤩

In this article, we’re not going to use any 3rd party library, Just Geolocation API.
First, create your react app using this command,

`npx create-react-app geolocation`

Now let’s create one component called GeoLocation.js in the src folder.
You can create a class or functional component, whatever you prefer, I’m creating a class component here!

we’re going to use [GeoLocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation) API which is supported by every browser.

First of all, we have to know that does this device supports GeoLocation? and for that, we will check using the condition as given below in the componentDidMount method!

```
componentDidMount() {
if (navigator.geolocation) {
alert(“GeoLocation is Available!”);
} else {
alert(“Sorry Not available!”);
}}
```
In this code,
**Navigator:** It is an interface that represents the state and the identity of the user agent. Log this navigator, and you will see different properties such as geolocation.

In the above code if there is a geolocation property in navigator which means that the device supports location functionality.

Now we know that there is location functionality available, we have to check for permissions that if the user has permitted to access its location or not! for that we will use **navigator.permissions**.

{% gist https://gist.github.com/codebucks27/70edb9c9e5f7951b2bbf80dc3d6d8ae7 %}

Let me explain this code,

In the componentDidMount method,
after the if condition we have to put **navigator.permissions** to know the permissions we have.

Now this **navigator.permission.query({name : “geolocation”})** will query the permission status for geolocation.

Then it will return a result object which contains a state like,

**“granted”** — We have permission to access location, so we can call our function directly!
**“prompt”** — User will get a popup asking for permission!
**“denied”** — User denied sharing location.

For **“granted”** and **“prompt”** state we can create a function to get the current position of the user but for the “denied ”state, we can show instructions to how they can enable location permission in their browser.

>**NOTE:** There is no way you can prompt for location permission again if the user has already denied the location permission unless the user enables it manual in his browser.

Now we have permission to access location, let us get the current position of the user! To do that we are going to use the *getCurrentPosition()* method.

```
navigator.geolocation.getCurrentPosition(success[, error[, [options]])
```
It takes 3 arguments.

**success:** A callback function that takes an [`GeolocationPosition`](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition) object as its sole input parameter.

**error(optional):** An optional callback function that takes an [`GeolocationPositionError`](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError) object as its sole input parameter.

**options(optional):** An optional [`PositionOptions`](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object.

Options include:
* `maximumAge:` integer (milliseconds) | infinity - maximum cached position age.

* `timeout:` integer (milliseconds) - the amount of time before the error callback is invoked if 0 it will never invoke.

* `enableHighAccuracy:` false | true

Let’s add all these things in our code!

{% gist https://gist.github.com/codebucks27/6a96b155e6dd9668d790279ed3a7f71f %}

From line 3 to 19,

I have added options and two call back functions which are a **success(pos)** which gives us position object and **errors(err)** which will give us an error!

In line no 30: I have only passed **success** function because we are already granted permission!

In line no 32: We don’t know the permission state because it is prompt now if the user allows then it will run **success** or it will show an **error**!

Below is the output in the console! (If you allow location permission)

>Your current position is:
GeoLocation.js:12 Latitude : 40.7128
GeoLocation.js:13 Longitude: 74.0060
GeoLocation.js:14 More or less 31 meters.

Now you can manipulate this code based on your requirements, I will suggest you use **console.log()** and log different objects to know more details about them.

That’s it! If you face any problem please comment below I will try my best to solve it and If you liked this article don’t forget to share it.

Also, If you want to learn about ReactJS, feel free to visit my Youtube Channel:

#[CodeBucks](https://www.youtube.com/channel/UCeYt6blRBKuNrEg_-282fSA)

Follow me on Twitter where I'm sharing lot's of useful resources!
####[@code.bucks](https://twitter.com/code_bucks) 😉

Thanks for reading. 😉😊