React Native Expo-Location 在初始使用期间返回位置服务不可用效果
Posted
技术标签:
【中文标题】React Native Expo-Location 在初始使用期间返回位置服务不可用效果【英文标题】:React Native Expo-Location returns Location service unavailable during initial useEffect 【发布时间】:2021-10-27 11:51:55 【问题描述】:主要问题:
我在我的 android 应用程序中使用 expo-location 来查找用户的 gps 坐标。我已阅读并使用了 expo 文档中提供的示例代码。我的主要问题是, Location.getCurrentPositionAsync() 返回Location provider is unavailable. Make sure that location services are enabled.
这是我下面的代码:
useEffect(() =>
(async () =>
let status = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted')
setErrorMsg('Permission to access location was denied');
return;
let location = await Location.getCurrentPositionAsync();
console.log(location);
)();
, []);
状态返回 granted
但 getCurrentPositionAsync()
返回错误。我通过使用 try-catch 块并在 catch 块中再次运行 getCurrentPositionAsync()
实现了一个 janky 解决方案,这似乎有效。这是我下面的代码:
useEffect(() =>
(async () =>
let status = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted')
setErrorMsg('Permission to access location was denied');
return;
try
var location = await Location.getCurrentPositionAsync();
catch
location = await Location.getCurrentPositionAsync();
console.log(location);
)();
, []);
有人知道为什么会这样吗?
编辑:我尝试使用他们的快餐示例运行发布在 expo-location 文档中的示例代码。结果相同。这可能是我的电话/区域的问题吗?我用两部手机测试过,都返回同样的错误。
【问题讨论】:
我有同样的问题,我认为是Android 11+的权限问题;测试一下: let BackgroundPermissions = await Location.requestBackgroundPermissionsAsync(); console.log(BackgroundPermissions: BackgroundPermissions); 【参考方案1】:我认为location
变量不能直接记录/使用,这是我检索location
的方式:
let status = await Location.requestPermissionsAsync();
let location = await Location.getCurrentPositionAsync();
if (status !== 'granted') setErrorMsg('...');
const coords = location;
if (coords)
const latitude, longitude = coords;
【讨论】:
我尝试用requestForegroundPermissionsAsync()
来实现它。当我用模拟器尝试它时它可以工作,但它不适用于我的 Realme G90T 和 Mi 10。在我的手机上,它仍然返回相同的错误:位置提供程序不可用。确保已启用位置服务。
这意味着问题出在您设备上的定位服务中。您可以在设备的设置中查看它以上是关于React Native Expo-Location 在初始使用期间返回位置服务不可用效果的主要内容,如果未能解决你的问题,请参考以下文章
react native 增加react-native-camera
更新 react-native-maps 以使用 create-react-native-app
react native 增加react-native-storage
React-Native 和 Expo:create-react-native-app 和 react-native init 之间的区别
什么是 react-native-cli 和 @react-native-community/cli?
React Native - 当 react-native 版本 > 0.55 时,无法通过 react-native-cli 创建新项目