如何在expo-location中获取当前精度值并在精度不足时触发警告?
实现方案
前置配置
- 安装指定版本依赖:
npx expo install expo-location@~13.0.4 - 配置平台权限:
- iOS:在
app.json的ios.infoPlist字段中添加NSLocationWhenInUseUsageDescription、NSLocationAlwaysAndWhenInUseUsageDescription权限说明 - Android:在
app.json的android.permissions字段中添加ACCESS_FINE_LOCATION、ACCESS_COARSE_LOCATION权限
- iOS:在
核心代码实现
import React, { useEffect, useRef } from 'react'; import { View, Alert, Text } from 'react-native'; import * as Location from 'expo-location'; export default function GPSTestScreen() { // 警告防抖标记,避免短时间重复弹出提示 const warnLockRef = useRef(false); // 位置订阅实例引用 const locationSubRef = useRef(null); useEffect(() => { const initLocationMonitor = async () => { // 请求前台位置权限 const permissionRes = await Location.requestForegroundPermissionsAsync(); if (permissionRes.status !== 'granted') { Alert.alert('权限错误', '未获取位置权限,无法监测GPS精度'); return; } // 订阅实时位置更新 locationSubRef.current = await Location.watchPositionAsync( { // 配置最高精度采集,确保精度值准确 accuracy: Location.Accuracy.Highest, // 位置更新间隔,可根据需求调整 timeInterval: 2000, distanceInterval: 2 }, (location) => { const currentAccuracy = location.coords.accuracy; // 精度小于4且未加锁时触发警告 if (currentAccuracy < 4 && !warnLockRef.current) { Alert.alert('精度警告', `当前GPS精度值为${currentAccuracy},低于阈值4`); // 加锁1分钟,避免重复提示 warnLockRef.current = true; setTimeout(() => { warnLockRef.current = false; }, 60000); } } ); }; initLocationMonitor(); // 组件卸载时取消订阅,避免内存泄漏 return () => { locationSubRef.current?.remove(); }; }, []); return ( <View> <Text>GPS精度监测运行中</Text> </View> ); }
注意事项
expo-location的Location.Accuracy枚举值天然对应1-6的取值范围,1为最低精度,6为最高精度,不需要额外做数值映射- 代码中的防抖逻辑可以根据业务需求调整,也可以直接删除实现每次精度低于阈值都触发提示
- 如果需要后台持续监测精度,需要额外申请后台位置权限,同时配置对应平台的权限声明
内容的提问来源于stack exchange,提问作者OyeeRatio
相关产品推荐
相关产品推荐

