How to Use Geolocation in React Native With Hooks
An illustrative introduction to the Geolocation API in React Native
To get started using the Geolocation API in React Native, you’ll need to ensure that you have created a React Native project using
expo-cli. If you haven’t already, you can create a new app using the
react-native-cli by doing the following.
Installing the React Native CLI via npm:
npm i -g react-native-cli
Creating a new React Native project:
react-native init geolocation-project
Now that we have a React Native project set up, we’ll need to install the React Native Geolocation module and link it to our native modules. Previously, the Geolocation API was provided directly from React Native, but it has since been moved out into its own npm package.
npm i @react-native-community/geolocation -S
Link (if using React Native CLI):
react-native link @react-native-community/geolocation
Using the API
The Geolocation API provides a couple of methods that we can leverage to retrieve the device’s geoposition:
watchPosition. If you just need to retrieve the position just once, and not listen for updates, then you’ll want to use
However, if you’d like to subscribe to updates and listen for changes in position, you’ll need to use
Let’s take a look at some examples of how we can use these methods in our react components.
Get current position
Here’s an example of how we can pull in the
getCurrentPosition method to display the current latitude and longitude to the user. This example also handles errors that may occur when trying to retrieve the position, and you can tweak this logic in the way that best suits your app.
Below, I’ve created a
useGeolocation hook by setting up a subscription using the
watchPosition method when the component mounts and then unsubscribes when the component unmounts. This hook will force a rerender when the current position changes and will return out the updated position on each update.
You’ll need to include
NSLocationAlwaysAndWhenInUseUsageDescription keys in your
Info.plist to enable geolocation when using the app.
If you need access to geolocation in the background, you’ll need to include the
NSLocationAlwaysUsageDescription key in
Info.plist as well and add location as a background mode in the
Capabilities tab in Xcode.
You’ll need to add the following to your
For more details, you can reference the README.
Hopefully this post helps you out and gives you a good idea of how you can start using the Geolocation API in React Native. Thank you for reading, and good luck with your projects.