0

I want to create a react native expo cli geolocation tracking system, i have got the location coordinates via expo location(lib).I have stored these co-ordinates into a variable(text) as a string. Now i want to display these coordinates in a map view in real time. How should i proceed?

Here is the code:

     import React, { useState, useEffect } from 'react';     //hooks for using react features without class 
    import { Platform, Text, View, StyleSheet } from 'react-native'; import Device from 'expo-device'; 
    import * as Location from 'expo-location';  //expo lib to get location coordinates 
    export default function App() {   const [location, setLocation] = useState(null); 
      const [errorMsg, setErrorMsg] = useState(null);  
     useEffect(() => {
            (async () => {
              if (Platform.OS === 'android' && !Device.isDevice) {
                setErrorMsg(
                  'Try it on your device!'
                );
                return;
              }
              let { status } = await Location.requestForegroundPermissionsAsync();
              if (status !== 'granted') {
                setErrorMsg('Permission to access location was denied');
                return;
              }
              let location = await Location.getCurrentPositionAsync({});
              setLocation(location);
            })();   }, []);  
     let text = 'Waiting..';   
if (errorMsg) {
            text = errorMsg;   } 
    else if (location) {
            text = JSON.stringify(location);   }  
     return (
            <View style={styles.container}>
              <Text style={styles.paragraph}>{text}</Text>
            </View>   ); } 
    const styles = StyleSheet.create({   container: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            padding: 20,   },   paragraph: {
            fontSize: 18,
            textAlign: 'center',   }, });

1 Answers1

0

Thanks, i got it done by myself:

here is the code:

import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import MapView from "react-native-maps";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";

const LOCATION_TASK_NAME = "background-location-task";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      region: null,
      error: '',
    };
  }

  _getLocationAsync = async () => {
    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      enableHighAccuracy: true,
      distanceInterval: 1,
      timeInterval: 5000
    });
    // watchPositionAsync Return Lat & Long on Position Change
    this.location = await Location.watchPositionAsync(
      {
        enableHighAccuracy: true,
        distanceInterval: 1,
        timeInterval: 10000
      },
      newLocation => {
        let { coords } = newLocation;
        // console.log(coords);
        let region = {
          latitude: coords.latitude,
          longitude: coords.longitude,
          latitudeDelta: 0.045,
          longitudeDelta: 0.045
        };
        this.setState({ region: region });
      },
      error => console.log(error)
    );
    return this.location;
  };

  async componentWillMount() {
    // Asking for device location permission
    const { status } = await Permissions.askAsync(Permissions.LOCATION);

    if (status === "granted") {
      this._getLocationAsync();
    } else {
      this.setState({ error: "Locations services needed" });
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <MapView
          initialRegion={this.state.region}
          showsCompass={true}
          showsUserLocation={true}
          rotateEnabled={true}
          ref={map => {
            this.map = map;
          }}
          style={{ flex: 1 }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff"
  }
});