Geolocation in React Native

2019-12-08

Let's see how to get user current geolocation to use react-native-geolocation-service library in React Native.

Outline

In this blog post, we’ll see how to get current geolocation in React Native. To get location information, we’ll use react-native-geolocation-service library. You can see the detail about react-native-geolocation-service library via the link below.

There is a source code about this blog post. If you want to see the source code, check the link below.

The example source code is based on the libraries below. If you want to know the details, check the links below.

How to install react-native-geolocation-service

Execute the link below to install react-native-geolocation-service.

npm install --save react-native-geolocation-service

we need to link the library to React Native project.

Version >= 0.60

Open ios/[project name]/Podfile file and modify it like below.

...
pod 'react-native-geolocation', path: '../node_modules/@react-native-community/geolocation'
...

After adding, execute the commands below to link react-native-geolocation-service to React Native project.

cd ios
pod install
cd ..

Version <= 0.59

If you use React Native version <= 0.59, see the official site links below.

Configure Android Permission

Open android/app/src/main/AndroidManifest.xml file and modify it like below to get user location information on Android.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.reactnativegeolocationserviceexample">

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

    <application

How to use

we can get the geolocation to use react-native-geolocation library like below.

How to get current geolocation

The code below is about how to get current geolocation.

Geolocation.getCurrentPosition(
    (position) => {
        console.log(position);
    },
    (error) => {
        // See error code charts below.
        console.log(error.code, error.message);
    },
    { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);

The example below is the full source code about how to get current geolocation.

import React, {useState, useEffect} from 'react';
import Styled from 'styled-components/native';
import Geolocation from 'react-native-geolocation-service';

const Container = Styled.View`
    flex: 1;
    justify-content: center;
    align-items: center;
`;

const Label = Styled.Text`
    font-size: 24px;
`;

interface ILocation {
  latitude: number;
  longitude: number;
}

const CurrentPosition = () => {
  const [location, setLocation] = useState<ILocation | undefined>(undefined);

  useEffect(() => {
    Geolocation.getCurrentPosition(
      position => {
        const {latitude, longitude} = position.coords;
        setLocation({
          latitude,
          longitude,
        });
      },
      error => {
        console.log(error.code, error.message);
      },
      {enableHighAccuracy: true, timeout: 15000, maximumAge: 10000},
    );
  }, []);

  return (
    <Container>
      {location ? (
        <>
          <Label>Latitude: {location.latitude}</Label>
          <Label>Latitude: {location.longitude}</Label>
        </>
      ) : (
        <Label>Loading...</Label>
      )}
    </Container>
  );
};

export default CurrentPosition;

You can see the result like below if use the source code above.

react-native-geolocation-service user current location

How to track user geolocation

We can not only get user current location, but also track user geolocation by react-native-geolocation-service.

The source code below is about how to track user gelocation.

_watchId = Geolocation.watchPosition(
  position => {
    const {latitude, longitude} = position.coords;
    setLocation({latitude, longitude});
  },
  error => {
    console.log(error);
  },
  {
    enableHighAccuracy: true,
    distanceFilter: 0,
    interval: 5000,
    fastestInterval: 2000,
  },
);

After tracking, we can stop it by the code below.

if (_watchId !== null) {
  Geolocation.clearWatch(_watchId);
}

The example below is the full source code about how to track user geolocation.

import React, {useState, useEffect} from 'react';
import Styled from 'styled-components/native';
import Geolocation from 'react-native-geolocation-service';

const Container = Styled.View`
    flex: 1;
    justify-content: center;
    align-items: center;
`;

const Label = Styled.Text`
    font-size: 24px;
`;

interface ILocation {
  latitude: number;
  longitude: number;
}

const WatchLocation = () => {
  const [location, setLocation] = useState<ILocation | undefined>(undefined);
  let _watchId: number;

  useEffect(() => {
    _watchId = Geolocation.watchPosition(
      position => {
        const {latitude, longitude} = position.coords;
        setLocation({latitude, longitude});
      },
      error => {
        console.log(error);
      },
      {
        enableHighAccuracy: true,
        distanceFilter: 0,
        interval: 5000,
        fastestInterval: 2000,
      },
    );

    return () => {
      if (_watchId !== null) {
        Geolocation.clearWatch(_watchId);
      }
    };
  }, []);

  return (
    <Container>
      {location ? (
        <>
          <Label>Latitude: {location.latitude}</Label>
          <Label>Latitude: {location.longitude}</Label>
        </>
      ) : (
        <Label>Loading...</Label>
      )}
    </Container>
  );
};

export default WatchLocation;

You can use the simulator for testing to track user location information. Open Debug > Location menu and choose one of City Run, City Bicycle Ride, Freeway Drive menu like the screen below. You can see the location changed.

react-native-geolocation-service tracking user location

Completed

We’ve seen how to get user location information by react-native-geolocation-service. Also, we’ve seen how to track user geolocation by watchPosition.

Buy me a coffeeBuy me a coffee
Posts