DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks
  • Common Problems in Redux With React Native
  • How To Integrate the Stripe Payment Gateway Into a React Native Application

Trending

  • Automatic Code Transformation With OpenRewrite
  • AI's Dilemma: When to Retrain and When to Unlearn?
  • Data Quality: A Novel Perspective for 2025
  • How Can Developers Drive Innovation by Combining IoT and AI?
  1. DZone
  2. Coding
  3. JavaScript
  4. How to Use Geolocation and Geocoding in React Native Apps

How to Use Geolocation and Geocoding in React Native Apps

By 
Prashant Gond user avatar
Prashant Gond
·
Dec. 18, 19 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
69.8K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will learn, how to implement Geolocation in a React Native application

Geolocation will find your current location and Geocoding gives your address (like City Name, Street Name, etc) by Coordinates (Latitude and Longitude).

What Is Geolocation?

The most famous and familiar location feature — Geolocation is the ability to track a device using GPS, cell phone towers, WiFi access points, etc. Geolocation uses positioning systems to trace an individual’s whereabouts right down to latitude and longitude, or more practically, a physical address. Both mobile and desktop devices can use Geolocation.

What Is Geocoding and Reverse Geocoding?

Geocoding is the method of remodeling an address or alternative description of a location into a (latitude, longitude) coordinate.

Reverse geocoding is the method of remodeling a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a very reverse geocoded location description might vary. For example, one would possibly contain the complete address of the closest building, whereas another could contain only a city name and postal code.

Post Structure

We will go step-by-step to explore Geolocation.

Steps


  • Create a simple React Native app.

  • Install Plugins for Geocoding and Geolocation and get user location.

  • Get a user's current location (Geocoding).

  • Convert user Geolocation into an address (Reverse Geocoding).

Three Major Objectives


  • Get user location in latitude and longitude (Geolocation).

  • Convert that latitude and longitude to street address (Reverse Geocoding).

  • Install plugins for Geocoding and Geolocation and get user location.

Step 1: Create a Simple React Native App

If you’re aware of native development, you’ll be familiar with React Native user interface.
It needs Xcode or Android Studio to get started.  If you already have one of these tools installed, you should be able to get up and running in minutes.

If they’re not installed, you should expect to spend about an hour installing and configuring them.

React Native CLI Quickstart
Assuming that you just have Node 10+ installed, you’ll be able to use npm to install the React Native cli command-line utility:

 npm install -g react-native-cli  

Then, run the following commands to create a new React Native project known as AwesomeProject:

 react-native init AwesomeProject

For details, you can check this link.

Step 2: React Native Geolocation Service

This library is created in an attempt to fix the location timeout issue on Android with the React Native implementation of Geolocation API. This library tries to solve the issue by using Google Play Service’s new FusedLocationProviderClient API, which Google strongly recommends over Android’s default framework location API. Which provider to use is based on your request configuration; it automatically decides and prompts you to change the location mode if it doesn’t satisfy your current request configuration.

Note: Location requests can still timeout, since many Android devices have GPS issues on the hardware level or in the system software level.

Installation:

Shell
 




x


 
1
yarn add react-native-geolocation-service
2
 
          
3
npm install react-native-geolocation-service



Setup

No additional setup is requried for Android. For iOS, follow these steps: 

To enable Geolocation in the background, you will include the NSLocationAlwaysUsageDescription key in Info.plist and add location as a background mode in the Capabilities tab in Xcode.

Update Your Podfile

Shell
 




xxxxxxxxxx
1


 
1
pod ‘react-native-geolocation’, path: ‘../node_modules/@react-native-community/geolocation’



Then, run pod install from the iOS directory.

Error Codes

NAME CODE DESCRIPTION
PERMISSION_DENIED 1 Location permission is not granted
POSITION_UNAVAILABLE 2 Location provider not available
TIMEOUT 3 Location request timed out
PLAY_SERVICE_NOT_AVAILABLE 4 Google play service is not installed or has an older version (android only)
SETTINGS_NOT_SATISFIED 5 Location service is not enabled or location mode is not
appropriate for the current request (android only)
INTERNAL_ERROR -1 Library crashed for some reason or the getCurrentActivity() returned null (android only)


Step 3: Get User Location (Geocoding)

Since this library was meant to be a drop-in replacement for the RN’s Geolocation API, the usage is pretty simple, with some further error cases to handle.

One issue to notice, this library assumes that location permission is already granted by the user, thus you have to use PermissionsAndroid to request permission to track user location before creating the placement request.

For obtaining user location, you have to import Geolocation API from a react-native-geolocation-service package like this.

import Geolocation from ‘react-native-geolocation-service’; 

Then, add this block to your code:

JavaScript
 




xxxxxxxxxx
1
16


 
1
if (hasLocationPermission) { 
2
    Geolocation.getCurrentPosition( 
3
        (position) => { 
4
            console.log(position); 
5
        }, 
6
        (error) => { 
7
            // See error code charts below. 
8
            console.log(error.code, error.message); 
9
        }, 
10
        { 
11
            enableHighAccuracy: true, 
12
            timeout: 10000, 
13
            maximumAge: 10000 
14
        } 
15
    ); 
16
}



So after adding all this code your file something look like this:


JavaScript
 




xxxxxxxxxx
1
17


 
1
componentDidMount() {
2
    Geolocation.getCurrentPosition(
3
        (position) => {
4
            console.log(position);
5
        },
6
 
          
7
        (error) => {
8
            // See error code charts below.
9
            console.log(error.code, error.message);
10
        },
11
        {
12
            enableHighAccuracy: false,
13
            timeout: 10000,
14
            maximumAge: 100000
15
        }
16
    );
17
}



Step 4: User Geolocation Into an Address (Reverse Geocoding)

We used a react-native-geocoding package for Geocoding and Reverse Geocoding. 

This module uses the Google Maps Geocoding API and requires an API key for quota management. Please check thislink to obtain your API key.

Installation

npm install –save react-native-geocoding 

You can just import Geocoder API from a react-native-geocoding package in your App.

import Geocoder from ‘react-native-geocoding’;  

And then you have to initialize the module in your app

JavaScript
 




x


 
1
Geocoder.init(“xxxxxxxxxxxxxxxx“); // use a valid API key
2
 
          
3
// With more options
4
 
          
5
// Geocoder.init(“xxxxxxxxxxxxxxxxxxx”, {language : “en”}); // set the language
6
 
          
7
//And use also this code for Geocoding and reverse Geocoding:
7
//And use also this code
8
 
          
9
    Geocoder.from(41.89, 12.49)
10
    .then(json => {
11
        var addressComponent = json.results[0].address_components[0];
12
        console.log(addressComponent);
13
    })
14
    .catch(error =>
15
        console.warn(error)
16
    );



A working example of Geolocation and GeoCoding to React-Native Apps.


JavaScript
 




xxxxxxxxxx
1
149
99


 
1
import React, {
2
    Component
3
} from 'react';
4
 
          
5
import {
6
    StyleSheet,
7
    Text,
8
    View
9
} from 'react-native';
10
 
          
11
import Geocoder from 'react-native-geocoding';
12
import Geolocation from 'react-native-geolocation-service';
13
 
          
14
export default class LocationDemo extends Component {
15
    constructor() {
16
        super()
17
        this.state = {
18
            latitude: 0,
19
            longitude: 0,
20
            error: null,
21
            Address: null
22
        }
23
    }
24
 
          
25
    async componentDidMount() {
26
        Geolocation.getCurrentPosition(
27
            (position) => {
28
                this.setState({
29
                    latitude: position.coords.latitude,
30
                    longitude: position.coords.longitude,
31
                });
32
 
          
33
                Geocoder.from(position.coords.latitude, position.coords.longitude)
34
 
          
35
                    .then(json => {
36
                        console.log(json);
37
 
          
38
var addressComponent = json.results[0].address_components;
39
                  this.setState({
40
                           Address: addressComponent
41
                        })
42
                        console.log(addressComponent);
43
                    })
44
                    .catch(error => console.warn(error));
45
            },
46
 
          
47
            (error) => {
48
                // See error code charts below.
49
                this.setState({
50
                        error: error.message
51
                    }),
52
                    console.log(error.code, error.message);
53
            },
54
 
          
55
            {
56
                enableHighAccuracy: false,
57
                timeout: 10000,
58
                maximumAge: 100000
59
            }
60
        );
61
    }
62
 
          
63
    render() {
64
        return (
65
            <View>
66
            <Text>
67
            <Text>
68
            <Text>
69
            {
70
                this.state.error ? < Text > Error : {
71
                    this.state.error
72
                } </Text> : null}
73
                </View>
74
            );
75
        }
76
    }
77
 
          
78
    const styles = StyleSheet.create({
79
        MainContainer: {
80
            flex: 1,
81
            justifyContent: 'center',
82
            backgroundColor: '#f5fcff',
83
            padding: 11
84
        },
85
        text: {
86
            fontSize: 22,
87
            color: '#000',
88
            textAlign: 'center',
89
            marginBottom: 10
90
        },
91
    });



Conclusion

In this blog, we learned how to implement the Geolocation React Native app. We also learned how to Convert Geocode in the Location address in a simple React Native app.

React Native mobile app React (JavaScript library)

Published at DZone with permission of Prashant Gond. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Cross-Platform Mobile Application Development: Evaluating Flutter, React Native, HTML5, Xamarin, and Other Frameworks
  • Common Problems in Redux With React Native
  • How To Integrate the Stripe Payment Gateway Into a React Native Application

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!