React Native Android 位置请求超时

React Native Android location request timed out

在 IOS 中,查找 GPS 坐标时没有问题。它工作正常。

在 Android 方面它不像 IOS 那样稳定。这个问题在真实设备和模拟器中都有。有时它可以找到位置,但有时不能。找了3天没找到解决办法

当我的应用程序找不到我的位置时,我尝试通过 Google 地图应用程序,它非常有用。

这是 IOS 和 Android 的代码;

getCurrentPosition() {
    navigator.geolocation.getCurrentPosition(
        (position) => {
            this.setState({ initialPosition: position });
            alert(JSON.stringify(position))
            var coords = new Coords();
            coords.Latitude = position.coords.latitude;
            coords.Longitude = position.coords.longitude;
            this.getPharmaciesByCoordinates(coords);
        },
        (error) => alert(error.message),
        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );
    this.watchID = navigator.geolocation.watchPosition((position) => {
        this.setState({ initialPosition: position });
    },
        (error) => alert(error.message),
        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
    );
}

欢迎任何类型的解决方案。

谢谢

我通过使用本机 LocationManager 的外部库找到了解决方案。它根据需要使用播放服务位置和发出位置事件。

这里是图书馆; https://bitbucket.org/timhagn/react-native-google-locations#readme

并且在为 android 编译时,不要忘记包含 android/app/build.gradle

dependencies {
    ...
    compile "com.google.android.gms:play-services:10.0.1" -> which version that you have write down here.
    ...
}

最后不要忘记在 Android SDK Manager 中下载 Google Play ServicesGoogle Support Library,您可以在其中找到您的播放服务版本;

<android-sdk-location>/<sdk-version>/extras/google/m2repository/com/google/android/gms/play-services

可能您在大楼或办公室内,信号不太好。我试过很多配置,这个最适合我:

{
    enableHighAccuracy: false,
    timeout: 5000,
    maximumAge: 10000
}

或者尝试增加超时时间。因为对我来说,通常的 2000 毫秒不起作用,所以我一直得到 "Location request timed out"。所以禁用高精度,增加超时,你就可以开始了。

诀窍是,如果你设置

{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 } 

然后就可以了。完整代码如下。

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class GeolocationExample extends Component {
constructor(props) {
super(props);

this.state = {
  latitude: null,
  longitude: null,
  error: null,
};
}

componentDidMount() {
navigator.geolocation.getCurrentPosition(
  (position) => {
    this.setState({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      error: null,
       });
       },
  (error) => this.setState({ error: error.message }),
  { enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 },
);}

 render() {
return (
  <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Text>Latitude: {this.state.latitude}</Text>
    <Text>Longitude: {this.state.longitude}</Text>
    {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
  </View>
  );
 }
}

export default GeolocationExample;

我在 Android 上删除了 maximumAge: 3600000 并且它有效

我已经根据位置请求完成了应用程序。命令
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }, 适用于 iOS 但不适用于 Android。我认为你应该检查平台。

navigator.geolocation.getCurrentPosition(
          (location) => {
            console.log('location ', location);
            if (this.validLocation(location.coords)) {
              this.locationToAddress(location.coords);
            }
          },
          (error) => {
            console.log('request location error', error);
          },
          Platform.OS === 'android' ? {} : { enableHighAccuracy: true, timeout: 20000, maximumAge: 10000  }
        );

我尝试了各种方法和 npm 模块。最后我通过使用这个模块解决了这个问题。我强烈建议这样做。 https://www.npmjs.com/package/react-native-geolocation-service

工作 { enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },

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

在 P 列表中添加权限并且 android 还显示

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null,
    };
  }

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },
      // { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
  }

  render() {
    return (
      <View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Latitude: {this.state.latitude}</Text>
        <Text>Longitude: {this.state.longitude}</Text>
        {this.state.error ? <Text>Error: {this.state.error}</Text> : null}
      </View>
    );
  }
}

您好,我遇到了同样的问题 "request time out "。 我已经尝试了我找到的所有可能的解决方案,但是这些对我不起作用,但最近我发现了一个模块可以解决这个问题。 react-native-geolocation-service 这对我有用......

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

Geolocation.getCurrentPosition(
      position => {
        const initialPosition = JSON.stringify(position);
        console.log(initialPosition);
      },
      error => Alert.alert('Error', JSON.stringify(error)),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
    );

这个功能对我有用,我已经用

更改了 "AndroidManifest.xml" 文件
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

在我的例子中,它在删除超时和 maximumAge 并将 enableHighAccuracy 设置为 false 后工作正常。

对于那些仍然面临问题的人,请注意参数。我曾经将参数保留为默认值,但当涉及到 enableHighAccuracy 时,您应该小心,因为当您将其设置为 false 时,这意味着您请求的是 WIFI 位置,而不是 GPS 位置。如果你不设置这个,你可能会像我一样在模拟器上收到错误。

Supported options:

timeout (ms) - Is a positive value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. Defaults to INFINITY.

maximumAge (ms) - Is a positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device will always return a cached position regardless of its age. Defaults to INFINITY.

enableHighAccuracy (bool) - Is a boolean representing if to use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested.

Detailed Documentation

编辑 1; 我建议大家使用这个库而不是为此类超时问题创建的原生库 (react-native-geolocation-service)。

删除参数 'maximumAge' 并保留

{ enableHighAccuracy: true, timeout: 2000}

我建议 2 种方法来考虑处理它:

  1. 使用 react-native-geolocation-service - 可以解决该问题的软件包。
  2. 尝试使用 enableHighAccuracy=true 调用一次,如果失败尝试使用 enableHighAccuracy=false 再次调用。
    详细信息:似乎 enableHighAccuracy=true 尝试通过 GPS 获取位置 - 当 enableHighAccuracy=false 时,设备首先尝试通过 Wifi 获取位置,如果失败,则尝试通过 GPS 获取。

下面是我如何实现数字 2 的:

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

const getCurrentLocation = (resolve, enableHighAccuracy, onError) => {
    console.log(`[getCurrentPosition] enableHighAccuracy=${enableHighAccuracy.toString()}`);

    Geolocation.getCurrentPosition(
        (position) => {
            const location = {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude
            }
            console.log('[getCurrentPosition] success');
            resolve(location);
        },
        onError,
        {enableHighAccuracy, timeout: 20000}
    );
};

/**
 * We first try to get location with enableHighAccuracy=true (try to get position via GPS) if it fails try to get it with enableHighAccuracy=false (try to get position from wifi)
 * @return {Promise}
 */
export const getCurrentPosition = () => {
    return new Promise((resolve) => {
        getCurrentLocation(resolve, true,
            (error1) => {
                // failed to retrieve with enableHighAccuracy=true - now try with enableHighAccuracy=false
                console.log(`[getCurrentPosition] failed 1st time trying again with enableHighAccuracy=false, error: ${error1.message}`);

                getCurrentLocation(resolve, false, (error2) => {
                    // Could not retrieve location - we can live with that
                    console.log(`[getCurrentPosition] failed ${error2.message}`);
                    resolve();
                })
            });
    });
}

我卡了3天,然后就白费了 我只是将超时值更改为 20000 毫秒。 现在问题已解决。

GetLocation.getCurrentPosition({ enableHighAccuracy:真, 超时:20000,

只需change/Increase“超时”值即可解决您的问题。

您可能需要检查您的 android 模拟器 GPS 是否启用。

转到选项(模拟器上的“⋮”)--> 位置--> 启用 GPS 信号应该已启用。

删除 timeoutmaximumAge 确实解决了 android 我这边的问题