我在这里找到位置有一个小问题
export default class App extends React.Component{
state = {
location: null
};
findCoordinates = () => {
Geolocation.getCurrentPosition(
position => {
const location = JSON.stringify(position);
this.setState({ location });
},
error => Alert.alert(error.message),
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
};
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>
);
}
}
他们未授予显示位置权限
答案 0 :(得分:6)
首先获得用户的位置许可。使用此功能
import { Platform, PermissionsAndroid } from 'react-native';
import Geolocation from 'react-native-geolocation-service';
async function requestPermissions() {
if (Platform.OS === 'ios') {
Geolocation.requestAuthorization();
Geolocation.setRNConfiguration({
skipPermissionRequests: false,
authorizationLevel: 'whenInUse',
});
}
if (Platform.OS === 'android') {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
}
}
答案 1 :(得分:3)
上述答案不再有效,因为 setRNConfiguration
函数现已弃用。
这是获取用户使用位置权限的更新方式:
import { Platform, PermissionsAndroid } from 'react-native';
import Geolocation from 'react-native-geolocation-service';
async function requestPermissions() {
if (Platform.OS === 'ios') {
const auth = await Geolocation.requestAuthorization("whenInUse");
if(auth === "granted") {
// do something if granted...
}
}
if (Platform.OS === 'android') {
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// do something if granted...
}
}
}
答案 2 :(得分:1)
请这样做
async function requestPermissions() {
if (Platform.OS === 'ios') {
const auth = await Geolocation.requestAuthorization('whenInUse');
if (auth === 'granted') {
_getCourts();
}
}
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
_getCourts();
}
}
}