访问当前位置并将其发送到Firebase

时间:2019-03-19 07:45:30

标签: firebase react-native react-native-maps react-native-firebase

我有一个我正在使用react-native-maps的react native应用程序。我想将当前位置发送到Firebase,并且还希望在用户从当前位置经过100米时向用户发出警报。我该怎么办?

其他信息:

  • 反应本机版本“ 0.57.5”
  • react-native-firebase“ ^ 5.2.3”
  • 本机映射“ ^ 0.22.1”

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以在安装组件后查询用户的当前位置,并继续侦听位置变化,然后计算不同位置之间的距离变化:

componentDidMount() {
    this.getLocation(); // Get users current location
}

componentDidUpdate(prevProps, prevState) {
    // If prevState changes
    if (prevState.newLatitude !== this.state.newLatitude) {
        // calculate the distance between initial and new coordinates
        this.getDistance();
    }
}

componentWillUnmount() {
    // Remember to clear all listeners
    navigator.geolocation.clearWatch(this.watcher);
}

getLocation() {
    navigator.geolocation.getCurrentPosition((position) => {
        this.setState({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
        }, () => {
            this.sendToFirebase();
            this.watchUserPosition(); //continue listening for location changes
        });
    },
    (error) => {
        //Handle error
    },
    { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
    );
}

watchUserPosition() {
    this.watcher = navigator.geolocation.watchPosition(
      (position) => {
        this.setState({
          newLatitude: position.coords.latitude,
          newLongitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
    );
  }

现在,在获得初始经度和纬度之后,可以继续比较从watchUserPosition获得的新经度和纬度。这将等于将经度和纬度转换为米,并检查以米为单位的初始坐标和以米为单位的新坐标的差异。

为此,您可以使用Geolib library

getDistance() {
    let initial = {latitude: this.state.latitude, longitude: this.state.longitude};
    let newCoord = {latitude: this.state.newLatitude, longitude: this.state.newLongitude};
    const distance = geolib.getDistance(initial, newCoord);
    if (distance >== 100) {
        Alert.alert("Success!", "You have reached 100meters!");
        this.sendToFirebase(); // whatever you are saving to firebase
    }
}

或者,您可能要考虑使用Firebase Geo-Fire