React Native - 地理位置

在本章中,我们将向您展示如何使用地理位置

步骤 1:App.js

import React from 'react'
import GeolocationExample from './geolocation_example.js'

const App = () => {
   return (
      <GeolocationExample />
   )
}
export default App

步骤 2:地理定位

我们首先设置初始状态,该状态将保存初始位置和最后位置。

现在,我们需要使用 navigator.geolocation.getCurrentPosition 获取安装组件时设备的当前位置。我们将对响应进行字符串化,以便更新状态。

navigator.geolocation.watchPosition 用于跟踪用户的位置。我们还在此步骤中清除观察者。

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,
      alignItems: 'center',
      marginTop: 50
   },
   boldText: {
      fontSize: 30,
      color: 'red',
   }
})