Search code examples
react-nativegoogle-mapsgeolocationmapstracking

How to create live tracking in react native?


Can anyone tell me please , how to create live tracking in react native ? Using geolocation ,react native maps or other dependencies, i wanna make a tracking driver like uber


Solution

  • Hope you have installed react-native-maps and added the necessary packages to your application. Use the below given code in componentDidMount(). The below given code will be called whenever your location will be changed. and it will provide you the updated location. Here you will also find the heading, you can use heading to show the vehicle direction or alignment.

    this.watchId = navigator.geolocation.watchPosition(
      (position) => {
        this.locationPermission = true;
        console.log('Watch Position response', position);
        const { coordinate } = this.state;
        const { latitude, longitude } = position.coords;
        const newCoordinate = {
          latitude,
          longitude
        };
        if (Platform.OS === 'android') {
          if (this.marker) { this.marker._component.animateMarkerToCoordinate(newCoordinate, 500); }
        }
        else {
          coordinate.timing(newCoordinate).start();
        }
    
        this.setState({
          marker: {
            latlng: {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude,
            }
          },
          heading: position.coords.heading,
        })
    
    
        );
    
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
    );