React Native - 地理位置

React Native - 地理位置 首页 / React Native入门教程 / React Native - 地理位置

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

MethodDescription
getCurrentPosition()它使用最新的位置信息调用一次成功回调。
watchPosition()每当位置更改时,它都会调用成功回调。它返回一个watchId(数字)。
clearWatch()清除watchPosition()的watchId。
stopObserving()它停止观察设备位置更改,并删除以前注册的所有侦听器。
setRNConfiguration()它设置配置选项,该选项将在所有位置请求中使用。
requestAuthorization()它基于在pList上配置的密钥请求合适的位置许可。

步骤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',
   }
})
React Native Geolocation

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

如何做好一场技术演讲 -〔极客时间〕

DDD实战课 -〔欧创新〕

打造爆款短视频 -〔周维〕

零基础实战机器学习 -〔黄佳〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

JavaScript进阶实战课 -〔石川〕

Dubbo源码剖析与实战 -〔何辉〕

快速上手C++数据结构与算法 -〔王健伟〕

AI大模型企业应用实战 -〔蔡超〕

好记忆不如烂笔头。留下您的足迹吧 :)