你能用 React Native 跟踪背景地理定位吗?

Can you track background geolocation with React Native?

问题

即使应用程序不再位于前台(例如,用户已切换到另一个应用程序或切换到主屏幕并锁定了他们的 phone,我也希望能够跟踪用户位置).

用例是用户跟踪 运行。他们可以打开应用程序并在 运行 开头按 'start',然后切换或最小化应用程序(按主页按钮)并锁定屏幕。在 运行 结束时,他们可以将应用程序调到前台并按 'stop',应用程序会告诉他们在 运行.

上行驶的距离

问题

是否可以使用纯 React Native 在 iOS 和 Android 上跟踪背景地理定位?

关于地理定位的 React Native 文档 (https://facebook.github.io/react-native/docs/geolocation) 不是很清楚或详细。上面记录的链接避开了 iOS 上的背景地理定位(没有完全清楚)但没有提到 Android.

我最好使用 Expo 吗?

可以,但不使用 Expo,我看到了两个模块:

这是商业版,你必须购买许可证https://github.com/transistorsoft/react-native-background-geolocation

还有这个https://github.com/mauron85/react-native-background-geolocation

Expo 团队在 SDK 32 中发布了一项新功能,允许您在后台跟踪位置。

https://expo.canny.io/feature-requests/p/background-location-tracking

Webkit 目前正在评估 Javascript-only 解决方案。您可以添加您的声音 here

有关完整记录的 proof-of-concept 示例,请参阅 Brotkrumen

更新 2019 年世博会 33.0.0:

Expo 首先弃用其 SDK 32.0.0 以满足应用商店指南,但随后 reopened it in SDK 33.0.0

从那以后,他们让后台定位变得超级容易。使用我用来使后台地理定位工作的代码片段。

import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';

const LOCATION_TASK_NAME = 'background-location-task';

export default class Component extends React.Component {
  onPress = async () => {
    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      accuracy: Location.Accuracy.Balanced,
      timeInterval: 5000,
    });
  };

  render() {
    return (
      <TouchableOpacity onPress={this.onPress} style={{marginTop: 100}}>
        <Text>Enable background location</Text>
      </TouchableOpacity>
    );
  }
}

TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
  if (error) {
    alert(error)
    // Error occurred - check `error.message` for more details.
    return;
  }
  if (data) {
    const { locations } = data; 
    alert(JSON.stringify(locations); //will show you the location object
    //lat is locations[0].coords.latitude & long is locations[0].coords.longitude
    // do something with the locations captured in the background, possibly post to your server with axios or fetch API 
  }
});

代码很有魅力。需要注意的一件事是 您不能在 Expo 应用程序中使用地理定位。但是,您可以在独立构建中使用它。因此,如果您想使用后台地理定位,您必须使用此代码,然后执行 expo build:ios 并上传到应用商店,以便能够获取用户后台位置。

此外,请注意您必须包括

"UIBackgroundModes":[
          "location",
          "fetch"
        ]

app.json 文件的 info.plist 部分。

最流行的 RN 地理定位库是 https://github.com/react-native-geolocation/react-native-geolocation,它很容易支持这一点。与其他库相比,我更喜欢这个库,因为它会自动处理请求权限等问题,而且似乎具有最简单的 API.

只需这样做:

Geolocation.watchPosition((position)=>{
    const {latitude, longitude} = position.coords;
    // Do something.
})

除了包括后台模式 fetchlocation 以及适当的使用说明外,这不需要其他设置。

我发现它比 Expo 的 API 更有用,因为它不需要任何奇怪的顶级代码,也不需要我做除了创建手表位置处理程序之外的任何事情,这真的很棒.