And*_*han 1 react-native react-native-android
我在寻找位置时遇到了一个小问题,这是我的代码
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
他们显示未授予位置许可
上面的答案不再有效,因为该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...
}
}
}
Run Code Online (Sandbox Code Playgroud)
首先从用户获取位置许可。使用这个功能
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,
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5228 次 |
| 最近记录: |