反应本机地理位置GetCurrentPosition EnableHighAccuracy

时间:2019-09-12 19:30:41

标签: javascript android react-native geolocation

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

有人可以澄清为什么会这样吗?奇怪的是,该设置在不应该设置的情况下将其完全破坏。我不知道这是否与设备设置有关。如此笨拙的产品似乎有点危险。谢谢。

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

1 个答案:

答案 0 :(得分:2)

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

这是Geolocation中的错误。在Android上它将超时。如果您想要精确的位置并希望启用HighAccuracy,则应使用react-native-geolocation-service

library

中所述

“创建此库的目的是使用react-native的Geolocation API当前实现来解决android上的位置超时问题。”

也在React Native的官方site中推荐

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

尝试一下

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