React Native Geolocation GetCurrentPosition EnableHighAccuracy

Cos*_*ure 0 javascript android geolocation react-native

我在 Android 上使用 Geolocation 来获取用户的位置。我对 EnableHighAccuracy 设置有点困惑。基本上,要完成这项工作,我必须将其设置为 Android Simulator 的“true”和物理设备的“false”。否则它坏了,我得到超时错误并且没有位置。

有人可以澄清为什么会这样吗?奇怪的是,这个设置在不应该时完全破坏了它。我不知道这是否与设备设置或其他方面有关。这对生产来说似乎有点危险,因为这太hacky了。谢谢。

navigator.geolocation.getCurrentPosition(
 async (locationObj) => {
   //Some code
 },
 (error => Alert.alert("Could not get location"),
 { enableHighAccuracy: true, timeout: 15000 }
)
Run Code Online (Sandbox Code Playgroud)

小智 5

如果您将“enableHighAccuracy”设置为 true,那么它将使用 GPS 并且位置将是准确的。

这是Geolocation 中的一个错误。在 Android 上它会超时。如果您想要准确的位置并希望启用HighAccuracy 那么您应该使用react-native-geolocation-service

库中所述

“创建这个库是为了使用 react-native 当前的 Geolocation API 实现来修复 android 上的位置超时问题。”

也在React Native 的官方网站上推荐

“在 Android 上,它使用 android.location API。Google 不推荐此 API,因为它不如推荐的 Google Location Services API 准确且慢。为了与 React Native 一起使用,请使用 react-native-geolocation -服务模块。”

尝试这个

...
import Geolocation from 'react-native-geolocation-service';
...

componentDidMount() {
    // Instead of navigator.geolocation, just use Geolocation.
    if (hasLocationPermission) {
        Geolocation.getCurrentPosition(
            (position) => {
                console.log(position);
            },
            (error) => {
                // See error code charts below.
                console.log(error.code, error.message);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)