React Native Geolocation FlutterTPoint

In this tutorial we will learn how to get Geolocation in React Native. Generally many app uses Geolocation and perform event or any calculation for the user.

We will use two ways to fetch Geolocation. First is Geolocation NPM and second one is React Native function.

How to Fetch Geolocation using NPM In React Native?

There is a npm -> @react-native-community/geolocation to fetch the location in React Native. Install it and use as below example:

Run in your project’s terminal:

npm i @react-native-community/geolocation

Provide Permissions:

Android

Add following lines in your Manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

or

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

IOS

You need to include NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription in Info.plist to enable geolocation when using the app. If your app supports iOS 10 and earlier, the NSLocationAlwaysUsageDescription key is also required. If these keys are not present in the Info.plist, authorization requests fail immediately and silently. Geolocation is enabled by default when you create a project with react-native init.

Import the library:

import Geolocation from '@react-native-community/geolocation';

Then use:

Geolocation.getCurrentPosition(info => console.log(info));

Getting Current Location In React Native

componentDidMount() {
  if (hasLocationPermission) {
    Geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
        },
        (error) => {
          // See error code charts below.
          console.log(error.code, error.message);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
  }
}

You can explore more about it from here.

React Native Interview Questions. Don’s miss out these important question.

Thank you for visiting the page on FlutterTpoint. Hope you clear the Geolocation in RN. For any query, you can comment in the comment section below.

close

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment