React Native && Expo框架实战应用
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import * as Location from 'expo-location';
export default function App() {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
try {
const location = await Location.getCurrentPositionAsync({});
setLocation(location.coords);
} catch (error) {
setErrorMsg('Unable to get location: ' + error.message);
}
})();
}, []);
const getLocationHandler = async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
try {
const location = await Location.getCurrentPositionAsync({});
setLocation(location.coords);
} catch (error) {
setErrorMsg('Unable to get location: ' + error.message);
}
};
return (
<View style={styles.container}>
<Text style={styles.paragraph}>Latitude: {location ? location.latitude : 'N/A'}</Text>
<Text style={styles.paragraph}>Longitude: {location ? location.longitude : 'N/A'}</Text>
{errorMsg ? <Text style={styles.paragraph}>{errorMsg}</Text> : null}
<Button title="Get Location" onPress={getLocationHandler} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
padding: 10,
},
paragraph: {
margin: 8,
fontSize: 18,
textAlign: 'center',
},
});
这段代码使用React Native和Expo框架获取用户的当前位置。它首先请求前台定位权限,然后尝试获取位置信息。如果获取成功,它会显示纬度和经度;如果失败或者用户拒绝权限,它会显示错误信息。用户可以通过点击按钮手动尝试获取位置信息。这个例子展示了如何在React Native应用中使用异步函数和Expo API来处理位置服务。
评论已关闭