DEV Community

CodeBucks
CodeBucks

Posted on • Updated on

How to get user’s location with React JS

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 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!”);
}}
Enter fullscreen mode Exit fullscreen mode

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.

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]])
Enter fullscreen mode Exit fullscreen mode

It takes 3 arguments.

success: A callback function that takes an GeolocationPosition object as its sole input parameter.

error(optional): An optional callback function that takes an GeolocationPositionError object as its sole input parameter.

options(optional): An optional 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!

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

Follow me on Twitter where I'm sharing lot's of useful resources!

@code.bucks 😉

Thanks for reading. 😉😊

Top comments (10)

Collapse
 
matek075 profile image
Matek • Edited

Very useful article. Thank You :-)

Collapse
 
arjunkumardev profile image
ArjunKumarDev

Is this code will work on Safari browser?!? @codebucks

Collapse
 
shankar0295 profile image
Shankar

navigator.permissions not supported in safari. Try this instead

Inside function
const location = () => {
if ('geolocation' in navigator) {
/* geolocation is available /
navigator.geolocation.getCurrentPosition(success)
} else {
/
geolocation IS NOT available */
navigator.geolocation.getCurrentPosition(errors)
}
}

const success = async (pos) => {
    var crd = pos.coords;
    const res = await fetch(api)
    const location = await res.json();
    setUserLocation(location)
}

const errors = (err) => {
    alert(`ERROR(${err.code}): ${err.message}`);
}
Enter fullscreen mode Exit fullscreen mode

In jsx,
{!userlocation ? "India" : ${userlocation[0].name},${userlocation[0].country}}

Collapse
 
chattes profile image
Sourav Chatterjee

In safari , we can call
navigator.geolocation.getCurrentPosition(success, errors, options).
Tested and working in mac.

Collapse
 
codebucks profile image
CodeBucks

Based on this website I guess you can use it.

Collapse
 
arjunkumardev profile image
ArjunKumarDev

I have tried it,but it doesn't work...

Thread Thread
 
codebucks profile image
CodeBucks

I guess navigator.permissions is not supported in safari.

Collapse
 
cary1234 profile image
Cary

Thank you so much!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.