سلام و وقت بخیر خدمت کاربران محترم پی وی لرن و دوستان عزیزی که با آموزش فریم ورک React Native همراه مون هستند. در بخش های قبل با نحوه کار با انواع کامپوننت ها آشنا شدیم. در مورد نحوه استفاده از کامپوننت Alert در React Native بحث نمودیم. و حال می خواهیم مو ضوع رو در رابطه با استفاده از Geolocation در React Native ادامه دهیم. پس کار با Geolocation در React Native رو خواهیم داشت.
در این فصل ما به شما نحوه استفاده از Geolocation یا موقعیت جغرافیایی را نشان خواهیم داد.
مرحله ۱: App.js
1 2 3 4 5 6 7 8 9 | import React from 'react' import GeolocationExample from './geolocation_example.js' const App = () => { return ( <GeolocationExample /> ) } export default App |
مرحله ۲: موقعیت جغرافیایی یا Geolocation
ما با تنظیم وضعیت اولیه شروع می کنیم به خاطر این که اولین و آخرین موقعیت را نگه می دارد.
در حال حاضر، ما باید موقعیت فعلی دستگاه را هنگامی که یک کامپوننت با استفاده از navigator.geolocation.getCurrentPosition نصب شده است، دریافت کنیم. ما پاسخ را تشدید می کنیم تا بتوانیم وضعیت را به روز کنیم.
navigator.geolocation.watchPosition برای ردیابی موقعیت کاربران استفاده می شود. ما همچنین تماشاگران را در این مرحله فعال می کنیم.
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 | 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, alignItems: 'center', marginTop: 50 }, boldText: { fontSize: 30, color: 'red', } }) |
حال که در مورد نحوه کار با کامپوننت های مختلف و استفاده از Geolocation در React Native می دونیم ،می تونیم هر چه راحت تر و بهتر با راکت نیتیو کار کنیم و برنامه های کارامد تری داشته باشیم. در ادامه AsyncStorage رو خواهیم داشت.