React native 看起来应用程序没有';我没有权限访问react native中的位置

React native 看起来应用程序没有';我没有权限访问react native中的位置,react-native,react-native-android,React Native,React Native Android,我正在制作一个使用gps访问用户位置的应用程序 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 但这会产生一个错误,应用程序没有访问该位置的权限,我需要声明 <uses-permission androi

我正在制作一个使用gps访问用户位置的应用程序

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
但这会产生一个错误,应用程序没有访问该位置的权限,我需要声明

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

但问题并没有消失。我该怎么办呢?

如果您没有使用Promise,您应该使用
async Wait
。在你的代码中,它丢失了。获得许可后,您可以获得位置信息

async requestLocationPermission(){
试一试{
授予的常数=等待许可和ROID.request(
PERMISSIONS和roid.PERMISSIONS.ACCESS\u FINE\u位置,
{
“标题”:“示例应用程序”,
“消息”:“示例应用程序访问您的位置”
}
)
如果(已授予===权限sandroid.RESULTS.已授予){
log(“您可以使用该位置”)
警报(“您可以使用该位置”);
}否则{
console.log(“位置权限被拒绝”)
警报(“位置许可被拒绝”);
}
}捕捉(错误){
控制台。警告(错误)
}
}
异步组件didmount(){
等待requestLocationPermission()

}
当屏幕加载时,请求用户获得位置许可(对于API>23,请参见文档)。有关更多信息,请参阅此链接。如果用户允许位置权限,则显示位置,否则显示默认屏幕

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;
import React,{useffect,useState}来自“React”;
从“react native”导入{文本、视图、样式表、警报};
从“react native maps”导入MapView;
从“react native”导入{PermissionsAndroid};
const SearchScreen=()=>{
常量[纬度,设置纬度]=使用状态(“”);
const[longitude,setLongitude]=useState(“”);
const[grated,setgrated]=useState(“”);
useEffect(异步()=>{
授予的常数=等待许可和ROID.request(
权限和roid.PERMISSIONS.ACCESS\u位置,
{
标题:“位置权限”,
消息:“获取您的位置以发布请求”,
buttonNeutral:'稍后再问我',
按钮否定:“取消”,
buttonPositive:“OK”,
},
);
如果(已授予===权限sandroid.RESULTS.已授予){
navigator.geolocation.getCurrentPosition(位置=>{
设置纬度(位置坐标纬度);
设置经度(位置坐标经度);
});
设定值(真);
}
},[]);
const onUserPinDragEnd=(e)=>{
Alert.Alert(JSON.stringify(e))
};
如果(授予){
返回(
onUserPinDragEnd()}
title={“你在这里”}
协调={{
纬度:数字(纬度),
经度:数字(经度),
}}
/>
)
}否则{
返回(
未授予地图的权限
)
}
};
const styles=StyleSheet.create({
容器:{
…StyleSheet.absoluteFillObject,
身高:400,
宽度:400,
justifyContent:“柔性端”,
对齐项目:“居中”,
},
地图:{
…StyleSheet.absoluteFillObject,
},
});
导出默认搜索屏幕;

接受的答案对我来说很有效,但是因为我使用了钩子,所以我不得不以不同的方式定义
requestLocationPermission
方法

为LocationPermissionGrassed创建一个状态,该状态将在授予访问权限后更改

const [locationPermissionGranted, setLocationPermissionGranted] = useState(false);
设置
useffect
方法如下:

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 /> }
然后在代码的后面,根据状态值显示地图/位置,如下所示:

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 /> }
{locationpermissiongrated?:}

检查此更新,我添加了permissions和roid.request,但它不起作用。为将来的读者添加一些解释,说明您的代码如何解决问题我添加了说明。希望能有帮助