I am currently building a map application in React and needed to use the Geolocation API to get the user's current location. I'd like to share how I implemented it, so you can use it in your app too. In our example, we will build a simple application that will display the user's current latitude and longitude coordinates on a button click.
If you are interested to learn more about the Geolocation API, you can read about it here. Let's get right into it!
Getting Started
We will be using create-react-app to build our application.
In the App.js file, use the useState hook to declare the state variables for lat lng and status. lat and lng will store the latitude and longitude coordinates of the user's position. status will be used to keep track of loading and errors.
const [lat, setLat] = useState(null);
const [lng, setLng] = useState(null);
const [status, setStatus] = useState(null);
We will keep our return statement simple, displaying a , , and some tags.
<div className="App">
<button onClick={getLocation}>Get Location</button
<h1>Coordinates</h1>
<p>{status}</p>
{lat && <p>Latitude: {lat}</p>}
{lng && <p>Longitude: {lng}</p>}
</div>
We should have a basic app set up that looks something like this.
Geolocation API
Next, let's implement the Geolocation API to get the user's current location coordinates. You can check out more information on the Geolocation API here.
We will create a new function in our App component, called getLocation. This function will first check if navigator.geolocation is supported by your web browser. For the most part, it should be compatible with all browsers, except for some really old versions.
Once we check this, we can make a call to the navigator.geolocation.getCurrentPosition method. This function gets the user's current position and accepts 3 parameters; a success callback function, an error callback function (optional), and a position options object (optional).
If successful, we will set the latitude and the longitude. These values are stored in position.coords.latitude and position.coords.longitude.
If an error occurred, we will set the status to display an error.
In the position options object, you can enable high accuracy, set a timeout, or set a cached position age. We will leave these out for our example.
const getLocation = () => {
if (!navigator.geolocation) {
setStatus('Geolocation is not supported by your browser');
} else {
setStatus('Locating...');
navigator.geolocation.getCurrentPosition((*position*) => {
setStatus(null);
setLat(position.coords.latitude);
setLng(position.coords.longitude);
}, () => {
setStatus('Unable to retrieve your location');
});
}
}
We will then set a onClick listener to the button which will run the getLocation method whenever clicked. On your first time clicking the button, you will need to allow permission from your web browser. I'm using Google Chrome and it looks like this. This may look different depending on what web browser you are using.
Click allow and you should now see your latitude and longitude coordinates. (These are the default coordinates for Tokyo, Japan, by the way!)
The App.js file will look something like below.
import React, { useState } from "react";
const App = () => {
const [lat, setLat] = useState(null);
const [lng, setLng] = useState(null);
const [status, setStatus] = useState(null);
const getLocation = () => {
if (!navigator.geolocation) {
setStatus("Geolocation is not supported by your browser");
} else {
setStatus("Locating...");
navigator.geolocation.getCurrentPosition(
(position) => {
setStatus(null);
setLat(position.coords.latitude);
setLng(position.coords.longitude);
},
() => {
setStatus("Unable to retrieve your location");
}
);
}
};
return (
<div className="App">
<button onClick={getLocation}>Get Location</button>
<h1>Coordinates</h1>
<p>{status}</p>
{lat && <p>Latitude: {lat}</p>}
{lng && <p>Longitude: {lng}</p>}
</div>
);
};
export default App;
Wrapping Up
Thanks for reading! If you want to see the source code, you can check out my GitHub repo here. Now that you have the user's latitude and longitude coordinates, you can go on and use this for your application.
Before we end the article, here are three ideas of things you can build using the Geolocation API.