React Native Geolocation
The Geolocation API is used to get the geographical position (latitude and longitude) of a user. It extends the Geolocation web spec. This API is available through the navigator.geolocation globally so that we do not need to import it.
In Android, Geolocation API uses android.location API. However, this API is not recommended by Google because it is less accurate, and slower than the recommended Google Location Services API. To use the Google Location Services API in React Native, use the react-native-geolocation-service module.
React Native Configuration and Permissions
In this section, we discuss the project which is created using react-native init or with expo init or Create React Native App.
For iOS platform we include the NSLocationWhenInUseUsageDescription key in Info.plist to enable geolocation. Geolocation is by default enabled when a project is created with react-native init.
To enable geolocation in background, we need to include the 'NSLocationAlwaysUsageDescription' key in Info.plist. This requires adding location as a background mode in the 'Capabilities' tab in Xcode.
To access the location in Android, we need to add <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> in AndroidManifest.xml file.
The Android API >=23 requires to request the ACCESS_FINE_LOCATION permission using the PermissionsAndroid API.
Methods of Geolocation
React Native Geolocation Example
Note: We run the above code on Android Emulator, it has not GPS enabled. The latitude and longitude values are read from Emulator Extended controls (default value).