Open In App

Get current Geolocation of user using React-Geolocated

In some situations, applications need to access the current location properties of the user. Location properties include latitude, longitude, and some more about the current location of the user. From the Location properties, the user can know the current geolocation of the user.

Approach:

Prerequisites:

Steps to Create the React Application And Installing Module:

Step 1: To create a new react app, run the below command to your terminal.



npx create-react-app myapp

Step 2: Now, move inside the project directory using the below command.

cd myapp

Step 3: Install the react-Geolocated package inside your project directory by running the below command in the terminal.



npm install react-geolocated --save

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

  "dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-geolocated": "^4.1.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: Now, edit the app.js file and copy/paste the below code into it.




import React, { Component } from "react";
 
// Importing geolocated reducer function
import { geolocated } from "react-geolocated";
 
class App extends Component {
    render() {
 
        // Check geolocation supported in
        // browser or not
        return this.props.isGeolocationAvailable ? (
 
            // Check location is enable in
            // browser or not
            this.props.isGeolocationEnabled ? (
 
                // Check coordinates of current
                // location is available or not
                this.props.coords ? (
                    <div>
                        <h1 style={{ color: "green" }}>GeeksForGeeks</h1>
                        <h3 style={{ color: "red" }}>
                            Current latitude and longitude of the user is
                        </h3>
                        <ul>
                            <li>latitude - {this.props.coords.latitude}</li>
                            <li>longitude - {this.props.coords.longitude}</li>
                        </ul>
                    </div>
                ) : (
                    <h1>Getting the location data</h1>
                )
            ) : (
                <h1>Please enable location on your browser</h1>
            )
        ) : (
            <h1>Please, update your or change the browser </h1>
        );
    }
}
 
// Binding geolocated() reducer function to
// App component, while exporting it
export default geolocated()(App);

Step to run: To run the project, enter the below command to your terminal in the project directory.

npm start

Output:


Article Tags :