- React Native 教程
- React Native - 主页
- 核心概念
- React Native - 概述
- React Native - 环境设置
- React Native - 应用程序
- React Native - 状态
- React Native - 道具
- React Native - 样式
- React Native - Flexbox
- React Native - 列表视图
- React Native - 文本输入
- React Native - 滚动视图
- React Native - 图像
- 反应本机 - HTTP
- React Native - 按钮
- React Native - 动画
- React Native - 调试
- React Native - 路由器
- React Native - 运行 IOS
- React Native - 运行 Android
- 组件和 API
- React Native - 查看
- React Native - WebView
- React Native - 模态
- React Native - 活动指示器
- React Native - 选择器
- React Native - 状态栏
- React Native - 开关
- React Native - 文本
- React Native - 警报
- React Native - 地理定位
- React Native - 异步存储
- React Native 有用资源
- React Native - 快速指南
- React Native - 有用的资源
- React Native - 讨论
React Native - 地理定位
在本章中,我们将向您展示如何使用Geolocation。
第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',
}
})