Latitude and Longitude are two imaginary lines draw on earth’s map to locate any place on Earth. Latitude is the distance of north or south of the equator (an imaginary circle around the Earth halfway between the North Pole and the South Pole) like a horizontal line between earth. Longitude is distance east or west of the prime meridian like a vertical line connecting both North pole and South pole. You can see the below image to know how exactly Latitude and Longitude are . So in this tutorial we would going to Get Device Current Location Latitude Longitude in react native android iOS application example tutorial using geolocation.watchPosition() method, There is no need to import this library. So let’s get started .
Contents in this project Get Device Current Location Latitude Longitude in React Native Android iOS App Example Tutorial:
Configure Project for Android Devices:
To get current latitude and longitude of device we need to use the android’s Requesting runtime permission structure in our application, So read my this tutorial about Android Requesting Runtime GPS permission and follow all the steps of my tutorial to enable runtime permission functionality in your app. Without enabling runtime permission you won’t be able to retrieve current location in android.
Configure Project for iOS Devices:
1. To configure your project in iOS devices we need to put below NSLocationAlwaysAndWhenInUsageDescription, NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription permissions in YourReactNativeProject -> ios -> YourProjectName -> info.plist file.
Note: These permissions are very important in order to access the device location in iOS mobile phones.
1
2
3
4
5
6
7
8
|
<key>NSLocationAlwaysAndWhenInUsageDescription</key>
<string>Always and in usage permissions</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>always permissions</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
|
Complete Source Code of my info.plist file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
<?xml version=“1.0” encoding=“UTF-8”?>
<!DOCTYPE plist PUBLIC “-//Apple//DTD PLIST 1.0//EN” “http://apple.com/DTDs/PropertyList-1.0.dtd”>
<plist version=“1.0”>
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>projnew</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>NSLocationAlwaysAndWhenInUsageDescription</key>
<string>Always and in usage permissions</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>always permissions</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>UIAppFonts</key>
<array>
<string>AntDesign.ttf</string>
<string>Entypo.ttf</string>
<string>EvilIcons.ttf</string>
<string>Feather.ttf</string>
<string>FontAwesome.ttf</string>
<string>FontAwesome5_Brands.ttf</string>
<string>FontAwesome5_Regular.ttf</string>
<string>FontAwesome5_Solid.ttf</string>
<string>Foundation.ttf</string>
<string>Ionicons.ttf</string>
<string>MaterialCommunityIcons.ttf</string>
<string>MaterialIcons.ttf</string>
<string>Octicons.ttf</string>
<string>SimpleLineIcons.ttf</string>
<string>Zocial.ttf</string>
</array>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
|
2. Open your react native project in Xcode and Select Your Project -> Select Your Project as Target -> Capabilities -> ON the Background Modes -> Enable Location Updates. See the below screenshot for more specific details. Click on the screenshot to see it in full size.
1. Import StyleSheet, Text, View, PermissionsAndroid, Alert and Platform component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, Text, View, PermissionsAndroid, Alert, Platform } from ‘react-native’;
|
2. Creating a async function class named as request_device_location_runtime_permission() in your project. Using this class we can ask for runtime permission to access the GPS location.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
export async function request_device_location_runtime_permission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
‘title’: ‘ReactNativeCode Location Permission’,
‘message’: ‘ReactNativeCode App needs access to your location ‘
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Alert.alert(“Location Permission Granted.”);
}
else {
Alert.alert(“Location Permission Not Granted”);
}
} catch (err) {
console.warn(err)
}
}
|
3. Create constructor() in your main export default class and make 3 States named as latitude, longitude and error.
1
2
3
4
5
6
7
8
9
10
11
12
|
constructor(){
super()
this.state={
latitude : 0,
longitude : 0,
error : null
}
}
|
4. Creating a async componentDidMount() method in your main class and call the request_device_location_runtime_permission() function with await method. Inside this method we would call the navigator.geolocation.watchPosition() method to access devices’s current latitude and longitude and save them inside Sates. The watchPosition() methods invokes every time when location changes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
async componentDidMount() {
if(Platform.OS === ‘android’)
{
await request_device_location_runtime_permission();
}
this.getLongLat = navigator.geolocation.watchPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 100, distanceFilter: 10 },
);
}
|
5. Creating componentWillUnmount() method and Inside this method we would call the navigator.geolocation.clearWatch() method. This would tell the app that after unmount the app you app doesn’t need access device location.
1
2
3
4
5
|
componentWillUnmount() {
navigator.geolocation.clearWatch(this.getLongLat);
}
|
6. Creating 2 Text component inside render’s return block and set the states values inside the Text component.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
render() {
return (
<View style={styles.MainContainer}>
<Text style={styles.text}> Latitude = {this.state.latitude}</Text>
<Text style={styles.text}> Longitude = {this.state.longitude}</Text>
</View>
);
}
|
7. Creating Style.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
backgroundColor: ‘#f5fcff’,
padding: 11
},
text:
{
fontSize: 22,
color: ‘#000’,
textAlign: ‘center’,
marginBottom: 10
},
});
|
8. Complete source code for App.js File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
import React, { Component } from ‘react’;
import { StyleSheet, Text, View, PermissionsAndroid, Alert, Platform } from ‘react-native’;
export async function request_device_location_runtime_permission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
‘title’: ‘ReactNativeCode Location Permission’,
‘message’: ‘ReactNativeCode App needs access to your location ‘
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Alert.alert(“Location Permission Granted.”);
}
else {
Alert.alert(“Location Permission Not Granted”);
}
} catch (err) {
console.warn(err)
}
}
export default class Project extends Component {
constructor(){
super()
this.state={
latitude : 0,
longitude : 0,
error : null
}
}
async componentDidMount() {
if(Platform.OS === ‘android’)
{
await request_device_location_runtime_permission();
}
this.getLongLat = navigator.geolocation.watchPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 100, distanceFilter: 10 },
);
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.getLongLat);
}
render() {
return (
<View style={styles.MainContainer}>
<Text style={styles.text}> Latitude = {this.state.latitude}</Text>
<Text style={styles.text}> Longitude = {this.state.longitude}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
backgroundColor: ‘#f5fcff’,
padding: 11
},
text:
{
fontSize: 22,
color: ‘#000’,
textAlign: ‘center’,
marginBottom: 10
},
});
|
Screenshots in Android device: