反应原生navigator.geolocation.getCurrentPosition不起作用

时间:2017-11-16 16:03:43

标签: android react-native geolocation navigator react-native-maps

我使用的是真正的Android设备(版本5.1)

我可以使用react-native-maps确定我的位置(在我的应用程序内的地图上正确的蓝点位置)+我可以使用谷歌地图应用程序并转到我的位置(GPS工作)。

我正在使用大超时,将enableHighAccuracy切换为true和false,删除选项等。所有人都没能得到navigator.geolocation来获取数据。

这是我的代码:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
};

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
};

navigator.geolocation.getCurrentPosition(success, error, options);

我得到:ERROR(3): Location request timed out

5 个答案:

答案 0 :(得分:6)

我知道为时已晚,但是它可以帮助其他人。

地理位置已从react native .60版本中提取。如果您需要替代解决方案

安装react-native-community / geolocation:

npm install @react-native-community/geolocation --save

react-native link @react-native-community/geolocation

然后,要请求访问位置,您需要将以下行添加到应用的AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

用法:

import Geolocation from '@react-native-community/geolocation';

Geolocation.getCurrentPosition(info => console.log(info));

答案 1 :(得分:5)

两件事。

1)如果没有缓存坐标,那实际上不是高精度响应的高超时 2)某些设备的高精度设置存在问题。

尝试将30000毫秒作为超时并删除高精度,直到找到一个有效的设置。

编辑:我发现了我记得React Native的长虫:https://github.com/facebook/react-native/issues/7495

所以,试试这个:

1)删除maximumAge属性 2)如果不起作用,请删除第三个参数并使用本机模块中的默认值。意思是,不要发送选项对象。这应该工作。

答案 2 :(得分:2)

删除maximumAge在这里解决了这个问题!万一有人在2019年仍然遇到这个问题

答案 3 :(得分:1)

我使用了它,并且效果很好: {enableHighAccuracy:false,timeout:50000}

async watchPosition() {
    console.log('watchPosition');        
    await navigator.geolocation.getCurrentPosition(
        (position) => {
          console.log('Position -> ',position);
        },
        (error) => console.log(error)
        {enableHighAccuracy: false, timeout: 50000}
    );
}

答案 4 :(得分:1)

要请求访问位置,您需要在应用的AndroidManifest.xml中添加以下行:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

对于具有 API> = 23 的Android,您需要执行其他步骤进行检查:您需要使用ACCESS_FINE_LOCATION API来请求PermissionsAndroid权限。< / p>

PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        title: "Location Accessing Permission",
        message: "App needs access to your location"
      }
    );

并且只有在此之后运行navigator.geolocation.getCurrentPosition(success, error, options);

相关问题