React Native Tutorial
Core Concepts
Components and APIs
React Native Useful Resources
Selected Reading
Core Concepts
- React Native - Running Android
- React Native - Running IOS
- React Native - Router
- React Native - Debugging
- React Native - Animations
- React Native - Buttons
- React Native - HTTP
- React Native - Images
- React Native - ScrollView
- React Native - Text Input
- React Native - ListView
- React Native - Flexbox
- React Native - Styling
- React Native - Props
- React Native - State
- React Native - App
- React Native - Environment Setup
- React Native - Overview
Components and APIs
- React Native - AsyncStorage
- React Native - Geolocation
- React Native - Alert
- React Native - Text
- React Native - Switch
- React Native - Status Bar
- React Native - Picker
- React Native - ActivityIndicator
- React Native - Modal
- React Native - WebView
- React Native - View
React Native Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
React Native - Geolocation
React Native - Geolocation
In this chapter, we will show you how to use Geolocation.
Step 1: App.js
import React from react import GeolocationExample from ./geolocation_example.js const App = () => { return ( <GeolocationExample /> ) } export default App
Step 2: Geolocation
We will start by setting up the initial state for that will hold the initial and the last position.
Now, we need to get current position of the device when a component is mounted using the navigator.geolocation.getCurrentPosition. We will stringify the response so we can update the state.
navigator.geolocation.watchPosition is used for tracking the users’ position. We also clear the watchers in this step.
AsyncStorageExample.js
import React, { Component } from react import { View, Text, Switch, StyleSheet} from react-native class SwichExample extends Component { state = { initialPosition: unknown , lastPosition: unknown , } watchID: ?number = null; componentDidMount = () => { navigator.geolocation.getCurrentPosition( (position) => { const initialPosition = JSON.stringify(position); this.setState({ initialPosition }); }, (error) => alert(error.message), { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 } ); this.watchID = navigator.geolocation.watchPosition((position) => { const lastPosition = JSON.stringify(position); this.setState({ lastPosition }); }); } componentWillUnmount = () => { navigator.geolocation.clearWatch(this.watchID); } render() { return ( <View style = {styles.container}> <Text style = {styles.boldText}> Initial position: </Text> <Text> {this.state.initialPosition} </Text> <Text style = {styles.boldText}> Current position: </Text> <Text> {this.state.lastPosition} </Text> </View> ) } } export default SwichExample const styles = StyleSheet.create ({ container: { flex: 1, apgnItems: center , marginTop: 50 }, boldText: { fontSize: 30, color: red , } })Advertisements