How to Use the Geolocation API in Your React App

Get the user's coordinates and use them in your next React app

Photo by Denise Jans on Unsplash

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

Continue Learning