Get current Geolocation of user using React-Geolocated
Last Updated :
23 Nov, 2023
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:
- Geolocation Availability Check:
- The component verifies if geolocation is supported in the browser.
- Location Enablement Check:
- It checks whether the user has enabled location in the browser.
- Coordinate Availability Check:
- The component examines if the current latitude and longitude coordinates are available.
- Conditional Rendering with Styling:
- Based on the checks, it conditionally renders the coordinates with green and red styling or displays messages prompting location enabling or updating the browser.
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.
Javascript
import React, { Component } from "react" ;
import { geolocated } from "react-geolocated" ;
class App extends Component {
render() {
return this .props.isGeolocationAvailable ? (
this .props.isGeolocationEnabled ? (
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>
);
}
}
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...