react-nativelocationmobile-applicationpubnub

React Native Location Tracker


I'm implementing this code it is showing error like "undefined is not an object (evaluating 'navigator.geolocation.clearWatch')"

watchLocation = () => {
const { coordinate } = this.state;

this.watchID = navigator.geolocation.watchPosition(
  position => {
    const { latitude, longitude } = position.coords;

    const newCoordinate = {
      latitude,
      longitude,
    };

    if (Platform.OS === 'android') {
      if (this.marker) {
        this.marker._component.animateMarkerToCoordinate(newCoordinate, 500); // 500 is the duration to animate the marker
      }
    } else {
      coordinate.timing(newCoordinate).start();
    }

    this.setState({
      latitude,
      longitude,
    });
  },
  error => console.log(error),
  {
    enableHighAccuracy: true,
    timeout: 20000,
    maximumAge: 1000,
    distanceFilter: 30,
  }
);

};

Can anyone let me know how to solve this? Im referring this tutorial. Link


Solution

  • First install :

    npm i @react-native-community/geolocation
    

    Then -

    import Geolocation from '@react-native-community/geolocation';
    
    watchLocation = () => {
    const { coordinate } = this.state;
    
    this.watchID = Geolocation.watchPosition(
        //Your Code 
     );
    }
    

    For reference checkout - https://www.npmjs.com/package/@react-native-community/geolocation

    I've gone through the blog which you are following so according to that you'll have to do a change likewise :

    componentWillUnmount() {
      Geolocation.clearWatch(this.watchID);
    }