Tanmoy Sarker
Tanmoy Sarker

Reputation: 1266

Accessing current location and sending that to firebase

I have a react native app in which i am using react-native-maps.I want to send the current location to firebase and also i want to alert the user when he has passed 100 meter from the current location. How can i do that?

Additional Info:

Thanks in advance.

Upvotes: 0

Views: 1327

Answers (1)

LordKiz
LordKiz

Reputation: 643

You can query the user's current location when your component has mounted and continue listening for change in position and then calculate the change in distance from the different positions:

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

Now after you get the initial longitude and latitude, you can keep comparing the new longitude and latitude you are getting from watchUserPosition. This will amount to converting the longitudes and latitudes to metres and checking the differences of the initial coordinates in meters and new Coordinates in meters.

For this you can use the 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
    }
}

Alternatively you may want to consider using Firebase Geo-Fire

Upvotes: 1

Related Questions