How to use React Native Geolocation to get Postal Address

Published on Feb 25, 2021

10 min read



Geolocation in React Native applications is the ability to fetch the geographic position of the device when it is connected to the internet. It takes advantage of an API that provides the current location of the device in the form of Longitude and Latitude coordinates. It can be used to add features such as fetching simple location coordinates of a device or getting the current location of the device. Ultimately, Geolocation provides support to the development functionalities seen in delivery or ride-hailing applications.

In this tutorial, let's learn how you can implement a feature to get the current location of a device in a React Native app. To do this we’ll be using an API provided by Expo in the form of a package called expo-location. We will then convert the location coordinates into human-readable postal address format.

The source code is available at this GitHub repo.



To follow this tutorial, please make sure you are familiarized with JavaScript/ES6 and meet the following requirements in your local dev environment:

  • Have Node.js version >= 12.x.x installed.
  • Have access to one package manager such as npm or yarn or npx.
  • Have expo-cli installed, or use npx

Create a React Native app with expo-cli


Create a new React Native project using expo-cli and then install the dependencies required to build this demo app. Let's breakdown what we are going to implement:

  • The demo app is going to mimic a food delivery app feature where when an end-user opens the app, the first thing they are prompted for is to fetch their current location. Let's call this screen a Welcome screen.
  • Only once the location is fetched, will the end-user be taken to the Home screen of the app. This is a condition we are going to put in our demo.
  • We will be using a stack navigator from React Navigation library. This is just an example to understand the concepts of using Geolocation data in a React Native app. You can use the same concepts in the way you want to implement the feature of fetching the current location.

Open a terminal window and execute the following commands:

npx expo init expo-geolocation-example
# navigate into that directory
cd expo-geolocation-example
yarn add @react-navigation/native @react-navigation/stack
# install dependencies with Expo specific package version
expo install expo-location react-native-gesture-handler react-native-reanimated
react-native-screens react-native-safe-area-context

After installing these dependencies, let's create two mock screens that are going to be the two core screens for the demo app. Create a new screens/ directory and inside it, create the first screen file Welcome.js. This screen is going to display an image, a title, and a dummy mock location address for now. Later in this post, this dummy mock location address is going to display a real address based on the current location.

Add the following code snippet to this file:

1import React, { useState, useEffect } from 'react';
2import { StyleSheet, Text, View, Image } from 'react-native';
4const Welcome = ({ navigation }) => {
5 return (
6 <View style={styles.container}>
7 <View style={styles.contentContainer}>
8 <Image source={require('../assets/geo.png')} style={styles.image} />
9 <Text style={styles.title}>What's your address?</Text>
10 </View>
11 <Text style={styles.text}>Mock Address</Text>
12 </View>
13 );
16const styles = StyleSheet.create({
17 container: {
18 flex: 1,
19 backgroundColor: '#070707',
20 alignItems: 'center',
21 paddingTop: 130
22 },
23 contentContainer: {
24 alignItems: 'center',
25 marginBottom: 20
26 },
27 image: {
28 width: 150,
29 height: 150,
30 resizeMode: 'contain',
31 marginBottom: 20
32 },
33 title: {
34 fontSize: 22,
35 fontWeight: '700',
36 color: '#FD0139'
37 },
38 text: {
39 fontSize: 20,
40 fontWeight: '400',
41 color: '#fff'
42 }
45export default Welcome;

Create the second screen file Home.js with the following code snippet:

1import React from 'react';
2import { StyleSheet, Text, View } from 'react-native';
4const Home = ({ navigation }) => {
5 return (
6 <View style={styles.container}>
7 <Text>Home</Text>
8 </View>
9 );
12const styles = StyleSheet.create({
13 container: {
14 flex: 1,
15 backgroundColor: '#070707',
16 alignItems: 'center',
17 justifyContent: 'center'
18 }
21export default Home;

Let's hook up the stack navigation container in the App.js file since we do not have multiple files and different ways to navigate in this demo app. I am not going through how to set up and use the React Navigation library. If you'd like to learn more on that subject please go through the post How to Set Up and Use Navigators in React Native.

Open up the App.js file and add the following:

1import React from 'react';
2import { NavigationContainer } from '@react-navigation/native';
3import { createStackNavigator } from '@react-navigation/stack';
5// Custom screens
6import Welcome from './screens/Welcome';
7import Home from './screens/Home';
9const Stack = createStackNavigator();
11export default function App() {
12 return (
13 <NavigationContainer>
14 <Stack.Navigator initialRouteName="Welcome" headerMode="none">
15 <Stack.Screen name="Welcome" component={Welcome} />
16 <Stack.Screen name="Home" component={Home} />
17 </Stack.Navigator>
18 </NavigationContainer>
19 );

Once the navigator is set, you can open up a terminal window and run the command expo start. You can either choose an iOS simulator or an Android emulator or the Expo Go client app to view the results so far. Here is current the state of the demo app in an iOS simulator:

Check if the device's location service enabled


The first thing in the demo app we are going to implement is to check whether a device's location services are enabled or not. For this, let's create a state variable called locationServiceEnabled.

To check the status of the service let's create a new handler method called CheckIfLocationEnabled. The expo-location has an asynchronous method called Location.hasServicesEnabledAsync(). It returns a boolean value of true if the location service on the device is enabled and if otherwise, it returns false. In case of the value false, let's display an alert box indicating the same. If the location service is enabled, then update the value of the state variable using the setLocationServiceEnabled method.

The handler method is then called inside a useEffect React hook with no dependency such that it triggers only after the first render.

Modify the Welcome.js screen as shown below. Do note the placeholder message displayed in the place of the mock location address using a state variable called displayCurrentAddress. It will get an update once the current location of the device is found.

1import React, { useState, useEffect } from 'react';
2import { StyleSheet, Text, View, Image, Alert } from 'react-native';
3import * as Location from 'expo-location';
5const Welcome = ({ navigation }) => {
6 const [locationServiceEnabled, setLocationServiceEnabled] = useState(false);
7 const [displayCurrentAddress, setDisplayCurrentAddress] = useState(
8 'Wait, we are fetching you location...'
9 );
11 useEffect(() => {
12 CheckIfLocationEnabled();
13 }, []);
15 const CheckIfLocationEnabled = async () => {
16 let enabled = await Location.hasServicesEnabledAsync();
18 if (!enabled) {
19 Alert.alert(
20 'Location Service not enabled',
21 'Please enable your location services to continue',
22 [{ text: 'OK' }],
23 { cancelable: false }
24 );
25 } else {
26 setLocationServiceEnabled(enabled);
27 }
28 };
30 return (
31 <View style={styles.container}>
32 <View style={styles.contentContainer}>
33 <Image source={require('../assets/geo.png')} style={styles.image} />
34 <Text style={styles.title}>What's your address?</Text>
35 </View>
36 <Text style={styles.text}>{displayCurrentAddress}</Text>
37 </View>
38 );
41// styles remain same
43export default Welcome;

To test it out in the iOS simulator, go to Settings > Privacy > Location Services.

If it says on, as shown in the above image, tap it and make sure to switch off the Location Services.

Now open the app and you will notice that the alert box appears.

Similarly, on Android device, the location can be disabled from the following menu:

And the alert message will appear on the opening of the app:

Make sure to enable the location service again on the device before proceeding to the next section.

Get current location and postal address


It is necessary to request access to a device's information whether it is location or any other sensitive information. Fortunately, expo-location has methods that can be directly used when fetching the current location of the device.

Let's break down the steps on how we are going to fetch the current location of the device and obtain the information of the current address (which includes name, street name, city, and postal code) to display on the app screen.

  • First, create a new asynchronous handler method called GetCurrentLocation. Make sure to call it inside the useEffect hook after the previous code.
  • Inside it, using the Location API method requestPermissionsAsync, ask the device's user to grant permission for the location. If, in any case, the user denies it, display them an alert box stating the same.
  • If the permission is granted, get the current coordinates of the device's location using the Location API method getCurrentPositionAsync. The coordinates here are an object representing the location.
  • Then, when the coordinates object is present, destructure the value of Latitude and Longitude. The Location API has a method called reverseGeocodeAsync which reverses the geocode of a location to a postal address. Using the result from this, we can update the value of setDisplayCurrentAddress to display the device's current address.

Update the code snippet in Welcome.js as shown below:

1// first update the useEffect hook
2useEffect(() => {
3 CheckIfLocationEnabled();
4 GetCurrentLocation();
5}, []);
7// create the handler method
9const GetCurrentLocation = async () => {
10 let { status } = await Location.requestPermissionsAsync();
12 if (status !== 'granted') {
13 Alert.alert(
14 'Permission not granted',
15 'Allow the app to use location service.',
16 [{ text: 'OK' }],
17 { cancelable: false }
18 );
19 }
21 let { coords } = await Location.getCurrentPositionAsync();
23 if (coords) {
24 const { latitude, longitude } = coords;
25 let response = await Location.reverseGeocodeAsync({
26 latitude,
27 longitude
28 });
30 for (let item of response) {
31 let address = `${}, ${item.street}, ${item.postalCode}, ${}`;
33 setDisplayCurrentAddress(address);
34 }
35 }

Here is the output after this step:

The complete postal address is an object in JSON format and has the following fields (some of them might be useful for various cases):

1Object {
2 "city": "Stockholm",
3 "country": "Sweden",
4 "district": "Stockholm City",
5 "isoCountryCode": "SE",
6 "name": "Gustav Adolfs torg",
7 "postalCode": "111 52",
8 "region": "Stockholm",
9 "street": "Gustav Adolfs torg",
10 "subregion": "Stockholm",
11 "timezone": "Europe/Stockholm",

Once the location is fetched, we can send the current postal address as an object and navigate to the Home screen after a delay of two seconds using a setTimeout function.

Add the following code snippet after the statement setDisplayCurrentAddress(address):

1if (address.length > 0) {
2 setTimeout(() => {
3 navigation.navigate('Home', { item: address });
4 }, 2000);

Then, update the Home.js file to get the item object from route.params as well as its styles:

1import React from 'react';
2import { StyleSheet, Text, View } from 'react-native';
4const Home = ({ route }) => {
5 const { item } = route.params;
6 return (
7 <View style={styles.container}>
8 <View style={styles.contentContainer}>
9 <Text style={styles.title}>Home Delivery address: </Text>
10 <Text style={styles.text}>{item}</Text>
11 </View>
12 </View>
13 );
16const styles = StyleSheet.create({
17 container: {
18 flex: 1,
19 backgroundColor: '#070707',
20 alignItems: 'center',
21 justifyContent: 'center'
22 },
23 contentContainer: {
24 paddingHorizontal: 20,
25 alignItems: 'center'
26 },
27 title: {
28 fontSize: 22,
29 fontWeight: '700',
30 color: '#FD0139',
31 paddingBottom: 10
32 },
33 text: {
34 fontSize: 20,
35 fontWeight: '400',
36 color: '#fff'
37 }
40export default Home;

Here is the final output:

Further Reading


That's it! We hope you have found this tutorial helpful. We are adding some references for you to learn more about using Location API in Expo and React Native apps, plus which different packages can be used for your particular use case.

The source code is available at this GitHub repo.

Originally Published at Jscrambler's Blog

Share this article on Twitter

More Posts

Browse all posts

Join 1300+ devs & subscribe to my newsletter!


🔗 Subscribe on Revue


Software Developer and Technical Writer since 2017. Loves learning and writing about Node.js, React, React Native & Expo. Previously, a Developer Advocate at Draftbit.

Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.