反应本机地理定位 GetCurrentPosition EnableHighAccuracy

React Native Geolocation GetCurrentPosition EnableHighAccuracy

我在 Android 上使用地理定位来获取用户的位置。我对 EnableHighAccuracy 设置有点困惑。基本上,为了完成这项工作,我必须将其设置为 "true"(对于 Android 模拟器)和 "false"(对于物理设备)。否则它坏了,我收到超时错误并且没有位置。

谁能解释一下为什么会这样?奇怪的是,这个设置在不应该的时候完全打破了它。我不知道这是否与设备设置或其他原因有关。这对于生产来说似乎有点危险,因为它是如此骇人听闻。谢谢

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

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

这是 Geolocation . On Android it will timeout . if you want accurate location and want to enableHighAccuracy then you should use react-native-geolocation-service

中的错误

library所述

"This library is created in an attempt to fix the location timeout issue on android with the react-native's current implementation of Geolocation API."

React Nativesite官方也推荐

"On Android, this uses the android.location API. This API is not recommended by Google because it is less accurate and slower than the recommended Google Location Services API. In order to use it with React Native, use the react-native-geolocation-service module."

试试这个

...
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 }
        );
    }
}