Search code examples
geolocationreact-native

React Native Maps followUserLocation coordinates


Hi guys I need some help on how to get the coordinates of the user when you enable the

followUserLocation

on

MapView

. Is there a way on how to do this or are there any possible alternatives to this?

I already did something like this:

import {DeviceEventEmitter} from 'react-native';
import RNALocation from 'react-native-android-location';
import MapView from 'react-native-maps';

componentDidMount() {
    DeviceEventEmitter.addListener('updateLocation', function(e: Event) {
      console.log(e);
      this.setState({lng: e.Longitude, lat: e.Latitude });
    }.bind(this));
    RNALocation.getLocation();
 }

Already used React Native Geolocation https://facebook.github.io/react-native/docs/geolocation.html but nothing seems to work. It only gives me the initial location of the user and it does not give me some updates when there are changes on user location.

I even used setInterval to keep on calling the API so it can give me new updates on the user location but the coordinates still does not change.

I used fake GPS to move my location or mock my location . . please help thanks a lot.


Solution

  • Anyways, I got it all sorted out. Since there is no way I can listen to user location using the GPS of the mobile device. What I did was I used the code from React Native geolocation

    navigator.geolocation.getCurrentPosition(
      (position) => {
        var initialPosition = JSON.stringify(position);
        this.setState({initialPosition});
      },
      (error) => alert(JSON.stringify(error)),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    

    Loop through it every 1 second and then update the coordinate states (lat and long) if there is a change in coordinates. So far it works smoothly. :)