在ReactNative中使用地理位置
React Native 利用了网络原生的 Geolocation API。 此 API 返回 React Native polyfill 中可用的不同方法,例如 getCurrentPosition 和 watchPosition。 为了演示如何在 React Native 应用程序中使用它,我们将使用 react-native-cli 集成它。
入门
使用 react-native-cli 意味着没有模板,只有很少的样板代码可以开始。 我们将使用以下命令生成一个项目。 如果您还没有在本地机器上安装它,请使用下面提到的第一个命令:
# to install the cli $ npm install -g react-native-cli # to scafold an RN project $ react-native init geo-example
所以一旦生成了项目目录,就遍历进去,运行npm start看看是否一切安装正确。 如果你在 Mac 上,你可以使用 ios 模拟器来验证。 对于 Windows 和 Linux 用户,Android 模拟器将是您的朋友。
访问地理位置 API
Geolocation API 在 React Native 中以全局 navigator 对象的形式存在,就像在 Web 上一样。 它可以通过我们源代码中的 navigator.geolocation 访问,无需导入它。
出于演示目的,我们将使用 Geolocation API 中的 getCurrentPosition 方法。 此方法允许移动应用程序请求用户的位置并接受三个参数:成功回调、错误回调和配置对象。
navigator.geolocation.getCurrentPosition(
position => {
const location = JSON.stringify(position);
this.setState({ location });
},
error => Alert.alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
上面的成功回调有一个 position 参数,如果执行没有任何错误,它是一个具有以下属性的对象:
{
"timestamp": 1533729980953.91
"coords": {
"accuracy": 5,
"altitude": 0,
"altitudeAccuracy": -1,
"heading": -1,
"latitude": 37.785834,
"longitude": -122.406417,
"speed": -1
}
}
我们将在我们的 React Native 项目中修改 App.js 以开始使用。 我们首先定义一个显示文本 Find My Coords? 的基本类组件:
应用程序.js
import React, { Component } from "react";
import { View, Text } from "react-native";
export default class App extends Component {
render() {
return (
<View>
<Text>Find My Coords?</Text>
</View>
);
}
}
实施地理定位 API
现在,让我们在我们的应用程序中实现 Geolocation API 函数 getCurrentPosition。 打开 App.js 并编写以下代码。
应用程序.js
import React, { Component } from "react";
import {
Platform,
StyleSheet,
Text,
View,
Alert,
TouchableOpacity
} from "react-native";
export default class App extends Component {
state = {
location: null
};
findCoordinates = () => {
navigator.geolocation.getCurrentPosition(
position => {
const location = JSON.stringify(position);
this.setState({ location });
},
error => Alert.alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
};
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.findCoordinates}>
<Text style={styles.welcome}>Find My Coords?</Text>
<Text>Location: {this.state.location}</Text>
</TouchableOpacity>
</View>
);
}
}
我们开始导入 TouchableOpacity。 它是一个能够准确响应用户触摸的包装器。 在 React Native 移动应用程序中,您将经常使用该包装器组件。 将其视为 Web 应用程序中的按钮。 这个新导入的包装器接受一个 onPress 属性,它将触发指定的方法,在我们的例子中是 findCoordinates。
findCoordinates 包含获取用户位置的逻辑。 我们还使用本地状态来显示位置对象提供给我们的数据中的坐标。 文本 Find My Coords? 现在可以点击了。
让我们使用 React Native 的 StyleSheet 来修饰一下:
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10
},
instructions: {
textAlign: "center",
color: "#333333",
marginBottom: 5
}
});
此时,该示例将无法按预期工作。 我们需要请求访问用户位置的权限。 让我们接下来解决这个问题。
请求许可
在 iOS 中,使用 react-native-cli 创建项目时默认启用地理定位。 要使用它,您只需在 info.plist 文件中包含一个名为 <key>NSLocationWhenInUseUsageDescription</key> 的密钥,该文件位于 ios/findCoordsApp 目录中。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>findCoordsApp</string>
[..]
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>NSAppTransportSecurity</key>
<!--See http://ste.vn/2015/06/10/configuring-app-transport-security-ios-9-osx-10-11/ -->
[...]
</dict>
</plist>
对于 Android,我们需要在 android/app/src/AndroidManifest.xml 中添加以下行:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
包起来
现在,如果您运行应用程序,您将看到以下屏幕:
点击文本,系统会询问您是否允许应用程序请求用户位置:
如果按允许,您将看到以下结果屏幕:
那是一个非常简单的例子,但是你可以从那里去创造一些更有趣/有用的东西。 如果您想了解有关在 React Native 应用程序中使用 Geolocation API 的更多信息,请阅读 官方 文档。