Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
React Native

Tracking Location Using React Native in Android

2022-07-21

To track the location in react native we have ‘geolocation’. Geolocation support both ios and android. Before using the geolocation we need to request to access the user location by adding below line in android/app/src/main/AndroidManifest.xml.

...
    android:versionName="1">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Geolocation api exits on global navigator object, so we can access it via navigator.geolocation, and don't need to import as a react native component.

Possible methods for geolocation are

  • getCurrentPosition(success: Function, error?: Function, options?: GeoOptions)
  • watchPosition(success: Function, error?: Function, options?: GeoOptions)
  • clearWatch(watchID: number)

get Current Position

It is used to access user location at anytime.

Possible options are:

  • enableHighAccuracy(boolean) which allows us to get the accurate location.
  • timeout(milliseconds) by this we can give time interval to get position.
  • maximumAge(milliseconds)

if this method is called success function it will return present position information, otherwise it returns error.

For ex:

import  React, {Component} from ‘react’;
import { View, Text } from ‘react-native’;

export default class Geolocation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      latitude: null,
      longitute: null,
      timestamp: null
    }
  }
  
  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({ 
          latitude: position.coords.latitude ,
          longitute: position.coords.longitude
          timestamp:  position.timestamp
        })
      },
      (error) => { console.log(error); },
      { enableHighAccuracy: true, timeout: 30000 }
    )
  }
  
  render() {
    return  (
      <View>
        <Text>{this.state.latitude}</Text>
        <Text>{this.state.longitude}</Text>
        <Text>{this.state.timestamp}</Text>
      </View>
    )
  }
}

Here we can get the longitude and latitude, if we pass those values to google maps api we can get the location details in json format.

For example:

import  React, {Component} from ‘react’;
  import { View, Text } from ‘react-native’;

  const googleApiKey = ‘my_google_api_key’;
  export default class Geolocation extends Component {
    constructor(props) {
      super(props);
      this.state = {
        country: null
      }
    }
    
    componentDidMount() {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.getLocationDetails(position.coords.latitude,position.coords.longitude)
        },
        (error) => { console.log(error); },
        { enableHighAccuracy: true, timeout: 30000 }
      )
    }

    getLocationDetails(latitude, longitude) {
      const location = [];
      url='https://maps.googleapis.com/maps/api/geocode/json?address='+ latitude + ',' +longitude + '&key=' +  googleApiKey
      fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
          location = responseJson;
          location.results[0].address_components.forEach(component => {
            if (component.types.indexOf('country') !== -1) {
              this.setState({ country: component.long_name });
            }
          });
      });
    }
    
    render() {
      return  (
        <View>
          <Text>{this.state.country}</Text>
        </View>
      )
    }
  }

In above example we can get country name of current location.

watch Position

It is same as getCurrentPostition, but it invoked success function when the location is changed If you don't need real time update of present location then noo need of using this method.

clear Watch

It should be used only when the watchPosition is used. It will clear the previously stored watch id when the app is unmount.