使用 expo-location 获取不到位置信息 Location.getCurrentPositionAsync() 结果无打印
问题描述:
react native 中使用 expo-location 获取位置信息时,按照官方文档执行案例,获取不到位置结果。Location.requestForegroundPermissionsAsync() 执行后可以获取授权状态,但是执行到 Location.getCurrentPositionAsync() 时不会打印结果。
解决方法:
给 Location.getCurrentPositionAsync() 添加参数,如下
let location = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Highest, maximumAge: 10000, }); console.log("Location:", location);
官方文档:
- 安装:
npx expo install expo-location
- 使用:
下面是官方案例写法
import React, { useState, useEffect } from 'react'; import { Platform, Text, View, StyleSheet } from 'react-native'; import Device from 'expo-device'; import * as Location from 'expo-location'; export default function App() { const [location, setLocation] = useState(null); const [errorMsg, setErrorMsg] = useState(null); useEffect(() => { (async () => { if (Platform.OS === 'android' && !Device.isDevice) { setErrorMsg( 'Oops, this will not work on Snack in an Android Emulator. Try it on your device!' ); return; } let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { setErrorMsg('Permission to access location was denied'); return; } let location = await Location.getCurrentPositionAsync({}); setLocation(location); })(); }, []); let text = 'Waiting..'; if (errorMsg) { text = errorMsg; } else if (location) { text = JSON.stringify(location); } return ( <View style={styles.container}> <Text style={styles.paragraph}>{text}</Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 20, }, paragraph: { fontSize: 18, textAlign: 'center', }, });
官方案例中 getCurrentPositionAsync 方法传参为空对象 {} ,这是打印不出结果的原因。
添加参数后便可以获取结果数据。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了