看起来应用没有权限在React Native中访问位置

时间:2019-01-11 11:16:14

标签: react-native react-native-android

我正在制作一个使用gps访问用户位置的应用。这就是为什么我在AndroidManifest.xml中添加了以下几行

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

下面是我获取用户位置的函数

componentWillMount(){
    navigator.geolocation.getCurrentPosition(
      position => {

        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,

        });
      },
      error => Alert.alert(error.message),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );

  }

但是这会产生错误,表明应用没有访问位置的权限,我需要声明

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
在清单文件中

我尝试了很多方法并找到了解决方案,即要求运行时权限。所以我还在代码中添加了以下几行

try {
      const granted =  PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Location Permission',
          'message': 'This app needs access to your location',
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location")
      } else {
        console.log("Location permission denied")
      }
    } catch (err) {
      console.warn(err)
}

但是问题不会消失。我该怎么办?

3 个答案:

答案 0 :(得分:2)

接受的答案对我有用,但由于我使用钩子,我不得不以不同的方式定义 requestLocationPermission 方法。

为 locationPermissionGranted 创建一个状态,该状态将在授予访问权限后发生变化

const [locationPermissionGranted, setLocationPermissionGranted] = useState(false);

像这样设置 useEffect 方法:

useEffect(() => {
  async function requestLocationPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Example App',
          'message': 'Example App access to your location '
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location")
        alert("You can use the location");

        // Change the value of the locationPermissionGranted to true after
        // the user grants location access 
        setLocationPermissionGranted(true);
      } else {
        console.log("location permission denied");
        alert("Location permission denied");
      }
    } catch (err) {
      console.warn(err);
    }
  }

  // Don't forget to call the method here
  requestLocationPermission();
})

然后在您的代码中,根据状态值显示地图/位置,如下所示:

{ locationPermissionGranted ? <TestMapComponent /> : <AccessNotGrantedComponent /> }

答案 1 :(得分:0)

如果您未使用Promise,则应使用.GroupBy。在您的代码中缺失。在获得许可后,您可以获取位置

async-await

答案 2 :(得分:0)

在屏幕加载时,要求用户提供位置许可(根据文档,API> 23)。有关更多信息,请参见此链接https://facebook.github.io/react-native/docs/permissionsandroid。如果用户允许位置许可,则显示位置,否则显示默认屏幕。

import React,{useEffect,useState} from 'react';
import {Text,View,StyleSheet,Alert} from 'react-native';
import MapView from 'react-native-maps';
import {PermissionsAndroid} from 'react-native';

const SearchScreen = () => {
    const [latitude,setLatitude] = useState('');
    const [longitude,setLongitude] = useState('');
    const [granted,setGranted] = useState('');

    useEffect(async() =>{
        const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
            {
                title: 'Location Permission',
                message:'Get your location to post request',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            navigator.geolocation.getCurrentPosition(position => {
                setLatitude(position.coords.latitude);
                setLongitude(position.coords.longitude);
            });
            setGranted(true);
        }
    },[]);

    const onUserPinDragEnd = (e) => {
        Alert.alert(JSON.stringify(e))
    };

    if(granted) {
        return (
            <View style={styles.container}>
                <MapView
                    style={styles.map}
                    region={{
                        latitude: Number(latitude),
                        longitude: Number(longitude),
                        latitudeDelta: 0.015,
                        longitudeDelta: 0.0121
                    }}
                >
                    <MapView.Marker
                        key={'i29'}
                        draggable
                        onDragEnd={() => onUserPinDragEnd()}
                        title={'You are here'}
                        coordinate={{
                            latitude: Number(latitude),
                            longitude: Number(longitude),
                        }}
                    />
                </MapView>
            </View>
        )
    }else{
        return(
            <View>
                <Text>Permission not granted for maps</Text>
            </View>
        )
    }
};

const styles = StyleSheet.create({
    container: {
        ...StyleSheet.absoluteFillObject,
        height: 400,
        width: 400,
        justifyContent: 'flex-end',
        alignItems: 'center',
    },
    map: {
        ...StyleSheet.absoluteFillObject,
    },
});

export default SearchScreen;