Geolocation is used to find the current location of a network device. It can be used in applications like Google Maps, Uber, Tripadvisor, etc.
In ReactJS, we can find a user's current geolocation using the JavaScript Geolocation API.
Note: The Geolocation API is supported in a handful of broswers which can run HTML 5 such as Google Chrome, Opera, Edge, etc.
Now we will look at the steps that we need to follow in order to use the Geolocation API and find a user's latitude and longitude coordinates.
First, we will need to import react and the required libraries that will be used in this implementation. We will use the useState
react hook to manage the variable which stores a user's geolocation. We shall add the following line to include these libraries and methods at the start of our program.
import React, { useState } from 'react';
We will declare a component function called App()
for our React project, which will load the application page. There we will enclose all the geolocation methods.
Inside the App()
function, we will declare a userLocation
variable that stores the coordinates for the user's location. For this purpose, we will be using an useState react hook with its initial value set to null
.
const [userLocation, setUserLocation] = useState(null);
The next step is to define a function to find the user's geolocation and update the userLocation
variable accordingly. We will use the arrow function shown below.
const getUserLocation = () => { /*insert code here*/ };
In this getUserLocation
function, we will now add all the methods for finding the user's geolocation. First, we will check whether the geolocation functionality is supported by the user's browser. We will use a simple if else statement encasing the navigator.geolocation
function.
if (navigator.geolocation) {// what to do if supported}else {// display an error if not supportedconsole.error('Geolocation is not supported by this browser.');}
Now, we need to work on what to do if the navigator.geolocation
method is supported by the user's browser. We will need to retrieve the user's location. To do this, we use the navigator.geolocation.getCurrentPosition()
function.
navigator.geolocation.getCurrentPosition((position) => {// what to do once we have the position},(error) => {// display an error if we cant get the users positionconsole.error('Error getting user location:', error);});
Once we have the position of the user, we can now use it to find the user's coordinates and other relevant data. To access the coordinates that are enclosed in the position
variable, we can use the poisiton.coords
method. We will now create two variables to store these coordinates for later use.
const { latitude, longitude } = position.coords;
Once we have access to the user's coordinates, we will now update our userLocation
variable by calling the setUserLocation()
function.
setUserLocation({ latitude, longitude });
Now that we have stored the user's location coordinates, our next job is to render an HTML that will reflect back the user's coordinates onto the web page. To do this, we will include a button, and when its clicked, we will call the getUserLocation
function and update the userLocation
variable.
<button onClick={getUserLocation}>Get User Location</button>
We must also display the user location if we retrieve it successfully. To do this, we will use a &&
statement along with the userLocation
variable, which encloses all the HTML code to print the user's coordinates. Once the userLocation
variable updates, it is no longer a null value, and the statement is now true; hence it displays the coordinates.
{userLocation && (<div><h2>User Location</h2><p>Latitude: {userLocation.latitude}</p><p>Longitude: {userLocation.longitude}</p></div>)}
Now that we have gone through all the steps that we need to follow to retrieve a user's geographical location, we will now combine all the steps into a single file.
The following code represents how the App
component for our React app will be structured. It encloses all the methods which we have mentioned above and how they are to be implemented. Let's run the following widget.
// import the required react libraries import React, { useState } from 'react'; function App() { // const variable array to save the users location const [userLocation, setUserLocation] = useState(null); // define the function that finds the users geolocation const getUserLocation = () => { // if geolocation is supported by the users browser if (navigator.geolocation) { // get the current users location navigator.geolocation.getCurrentPosition( (position) => { // save the geolocation coordinates in two variables const { latitude, longitude } = position.coords; // update the value of userlocation variable setUserLocation({ latitude, longitude }); }, // if there was an error getting the users location (error) => { console.error('Error getting user location:', error); } ); } // if geolocation is not supported by the users browser else { console.error('Geolocation is not supported by this browser.'); } }; // return an HTML page for the user to check their location return ( <div> <h1>Geolocation App</h1> {/* create a button that is mapped to the function which retrieves the users location */} <button onClick={getUserLocation}>Get User Location</button> {/* if the user location variable has a value, print the users location */} {userLocation && ( <div> <h2>User Location</h2> <p>Latitude: {userLocation.latitude}</p> <p>Longitude: {userLocation.longitude}</p> </div> )} </div> ); } export default App;
To get the user's location, we shall have to open the application using the provided link above, as the browser has to get permission from us before it can access our location.
Free Resources