In this tutorial we’ll be building a location-sharing app with React Native and Pusher. By reading this tutorial, you will learn how to use the geolocation functionality in React Native, and broadcast the geolocation data with Pusher. You will also learn how to integrate Facebook login into the app.

Prerequisites

You will need the following in order to follow the tutorial:

  • React Native development environment – if you don’t have a machine setup for React Native development, be sure to check out the official docs on how to get started.
  • Genymotion Emulator – this is used for testing the app later on. You can actually use your Android smartphone as well, but Genymotion really makes it easy to test geolocation using their GPS emulator.
  • Pusher app – you’ll need to create a Pusher account in order to use Pusher’s services. A Pusher account is free to create and it even provides you with ample resources for testing the service. Once you have an account, create an app which will be used for connecting to Pusher.
  • Facebook app – this is required because we’ll be using Facebook login for the app.
  • Google project – this is required because Google Map is used for the map display.

In the following sections, I’ll be showing you how to create the Pusher, Facebook, and Google project.

Creating the Pusher App

Once you’re logged in to your Pusher account, go to your Dashboard and look for the menu for creating a new app. Set the name of the app to “locSharer”, and select the cluster nearest to your location. Click on the Create my app button to create the app. Once the app is created, click on the App Settings tab and enable Client Events. We need this because we’ll be sending events directly from the app. After that, click on the App Keys tab and copy the credentials somewhere where you can easily access it later on. We’ll be needing it later once we start configuring the app.

Creating the Facebook App

The minimum requirement for creating a Facebook app is for you to have a Facebook account. Once you’re logged in to your account, go to the Facebook developers website and create a new app. Set the Display Name to “locSharer”. Once the app is created, add Android as a platform then set the following details:
Google Play Package Name: com.locsharer
Class Name: com.locsharer.MainActivity

Next, generate a key hash to be used for development:

    keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

The command above generates a 28-character key hash. Paste the value under the Key Hashes field and save the changes. This step ensures the authenticity of the interactions between your app and Facebook, thus it’s a required step even for the development environment. You can find more information about this on the Facebook login documentation for Android.

Creating the Google Project

Just like Facebook, you need to have a Google account in order to create a Google project. Once you’re logged in to your Google account, go to the Google Developer Console and create a project. Set the project name to “locSharer”. Once the project is created, click on Enable APIs and Services button. From there, look for Google Maps Android API and enable it. Next, click on the Credentials tab and create an API key. Once the key is created, it will ask you to restrict access. Set the key restriction to Android. Then you can use the same keystore you used for Facebook:

    keytool -list -v -keystore ~/.android/debug.keystore

The command above allows you to get the sha1 hash. Look for it, copy the corresponding value and paste it under the SHA-1 certificate fingerprint field. Also enter the package name of the app (com.locsharer) then save the changes.

App Overview

As mentioned earlier, we will be creating a location-sharing app. First the user has to login with their Facebook account:

Once logged in, the user can enable location-sharing so that their friends can see their current location when they view them:

If the user has friends who are also using the app, they will be listed below the user’s details. Tapping on a friend will display a map which gets updated based on their current location (but only if they have enabled location sharing). The current location is indicated by a marker:

You can find the source code for this project on its Github repo.

Creating the Server

Just like every other Pusher app integration, this app needs a server component as well. The server’s job is to authenticate the requests coming from the app. This allows us to make sure that the request is indeed coming from the app and not anywhere else.

Start by creating a new folder for the server-related files. Inside the folder, run npm init to initialize a new project. Simply press enter until it asks you to confirm the project details. Once you get to that, just respond with yes.

Next, install the packages that we’ll be needing:

    npm install --save express body-parser pusher

Once the packages are installed, create a server.js file. Start by including the packages we just installed:

    var express = require('express');
    var bodyParser = require('body-parser');
    var Pusher = require('pusher');

    var app = express();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));

Next, add the code for connecting to Pusher. The Pusher app credentials are being loaded as environment variables. As you have seen from the code below, we’re not really using a module for loading environment variables from a .env file. Later I’ll show you how the values are being supplied.

    var pusher = new Pusher({ 
      appId: process.env.APP_ID, 
      key: process.env.APP_KEY, 
      secret:  process.env.APP_SECRET,
      cluster: process.env.APP_CLUSTER, 
    });

Add a route for verifying if the server is really working:

    app.get('/', function(req, res){ 
      res.send('server is running');
    });

Add the code for authenticating users that are connecting to your Pusher app. This contains the unique key that we will use later on to check whether the request has indeed come from the app.

    app.post('/pusher/auth', function(req, res) {
      var socketId = req.body.socket_id;
      var channel = req.body.channel_name;
      var auth = pusher.authenticate(socketId, channel);  
      var app_key = req.body.app_key;
      if(app_key == process.env.UNIQUE_KEY){
        var auth = pusher.authenticate(socketId, channel);
        res.send(auth);
      }

      res.send(auth);
    });

Initiate the server on the port set in the environment variables. Normally this would be served on port 80:

    var port = process.env.PORT || 5000;
    app.listen(port);

Deploying the Server

The server needs to be accessible via the internet. One service that allows us to do this for free is Now. **You can install Now **globally with the following command:

     npm install -g now

Once installed, you can now add your Pusher app credentials as a secret. One caveat of Now is that all the files for the deployed projects are available publicly. This means that the values in the .env files are publicly available as well. Adding those values as a secret means that it won’t be accessible anywhere.

    now secret add locshare_app_id YOUR_PUSHER_APP_ID
    now secret add locshare_app_key YOUR_PUSHER_APP_KEY
    now secret add locshare_app_secret YOUR_PUSHER_APP_SECRET
    now secret add locshare_app_cluster YOUR_PUSHER_APP_CLUSTER
    now secret add locshare_unique_key YOUR_UNIQUE_KEY

Don’t forget to replace the values with your actual Pusher app credentials.

Once that’s done, you can deploy the server:

    now -e APP_ID=@locshare_app_id -e APP_KEY=@locshare_app_key -e APP_SECRET=@locshare_app_secret APP_CLUSTER=@locshare_app_cluster -e UNIQUE_KEY=@locshare_unique_key

What the command above does is deploy the server, as well as setting the environment variables using the -e option. The secret values that you’ve added earlier are accessed by using the @ sign. When the process is completed, it should return a URL pointing to the server. Access that in the browser to check whether the server is running or not.

Creating the App

It’s now time to create the actual app. Start by generating a new React Native project:

    react-native init LocSharer

Installing and Configuring the Dependencies

Next install the dependencies of the app:

    npm install --save prop-types pusher-js react-native-facebook-login react-native-maps react-navigation

Here’s a brief overview of what each package does:
prop-types – for specifying the intended types of properties passed to components.
pusher-js – for interacting with Pusher.
react-native-facebook-login – for implementing Facebook login.
react-native-maps – for displaying Google Maps and markers.
react-navigation – for implementing Stack navigation within the app.

Additional steps are required in order for Facebook login and Google Maps to work. We’ll look at how to do that in the sections to follow.

Configuring Facebook Login

The following steps assumes that you have already created a Facebook app. So create one, if you haven’t done so already.

Once you’ve created a Facebook app, open the android/settings.gradle file and add the following to the bottom of the file:

    include ':react-native-facebook-login'
    project(':react-native-facebook-login').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-facebook-login/android')

Next, open the android/app/build.gradle file and add the following inside the dependencies:

    dependencies {
      ...
      compile project(':react-native-facebook-login')
    }

Next, register the React package by opening the android/app/src/main/java/com/{YOUR PACKAGE NAME}/MainApplication.java file, and adding the following:

    // top of the file
    import com.magus.fblogin.FacebookLoginPackage; // <--- add this

    public class MainApplication extends Application implements ReactApplication {

      ...

      @Override
      protected List<ReactPackage> getPackages() {
          return Arrays.<ReactPackage>asList(
              new MainReactPackage(),
              new FacebookLoginPackage() // <--- add this
          );
      }

      ...
    }

Next, open the android/app/src/main/res/values/strings.xml file and add the details of the Facebook app you created earlier:

    <resources>
      <string name="app_name">{YOUR FACEBOOK APP NAME}</string>
      <string name="fb_app_id">{YOUR FACEBOOK APP ID}</string>
      <string name="fb_login_protocol_scheme">fb{YOUR FACEBOOK APP ID}</string>
    </resources>

Lastly, open the android/app/src/main/AndroidManifest.xml file and add the following:

    <manifest 
      xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" <-- add this
      package="com.your.app.namespace">

      <application
        ...

        <!--add FacebookActivity-->
        <activity 
          tools:replace="android:theme"
          android:name="com.facebook.FacebookActivity"
          android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.Translucent.NoTitleBar"/>

        <!--add CustomTabActivity-->
        <activity
          android:name="com.facebook.CustomTabActivity"
          android:exported="true">
          <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
          </intent-filter>
        </activity>

        <!--add reference to Facebook App ID-->
        <meta-data
          android:name="com.facebook.sdk.ApplicationId"
          android:value="@string/fb_app_id"/>

      </application>
    </manifest>

Configuring React Native Maps

The following steps assumes that you have already created a Google project, and generated an API key.

Start by linking the package resources to your app:

    react-native link react-native-maps

Open the android\app\src\main\AndroidManifest.xml file and add a reference to your Google project’s API key:

    <application>
      ...
      <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="YOUR GOOGLE PROJECT'S ANDROID API KEY"/>
    </application>

Also add the following below the default permissions:

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

Coding the App

Now we’re ready to actually code the app. Start by opening the index.js file and replace the default contents with the following:

    import { AppRegistry } from 'react-native';
    import App from './App';

    AppRegistry.registerComponent('LocSharer', () => App);

The entry-point of the app will be the App component. So create an App.js file and add the following:

    import React, { Component } from 'react';
    import { StackNavigator } from 'react-navigation';

    import IndexPage from './src/components/index';
    import MapPage from './src/components/map_page';

    const Page = StackNavigator({
      Home: { screen: IndexPage },
      MapPage: { screen: MapPage },
    });

    export default class App extends Component<{}> {

      render() {
        return <Page />
      }
    }

The code above uses the React Navigation library to create a StackNavigator. This allows the app to transition from one screen to another by placing the new screen on top of the stack. This allows us to easily implement the back functionality since all it has to do is to “pop” the current screen out of the stack in order to go back to the previous screen. To use the StackNavigator, pass in the components to be used as the individual pages. The first one is the initial screen of the app.

Index Page

Next, create a src directory and inside create an index.js file. This will serve as the initial page of the app. First, import the modules and components that we need:

    import React, { Component } from 'react';
    import {
      StyleSheet,
      Text,
      View,
      Switch, // for toggling location sharing on and off
      DeviceEventEmitter // for emitting/listening custom events
    } from 'react-native';

    var { FBLogin } = require('react-native-facebook-login'); // for implementing Facebook login

    import Pusher from 'pusher-js/react-native'; // for interacting with Pusher

    import Profile from './profile'; // component for displaying the user's profile
    import Friends from './friends'; // component for displaying the user's friends

    import { regionFrom } from '../helpers'; // helper function for constructing the data needed by React Native Maps

Create the actual component:

    export default class Index extends Component<{}> {
      // set the title of the screen
      static navigationOptions = {
        title: 'LocSharer',
      };
    }

In the constructor, we bind the functions to be used throughout the class as well as setting the default state:

    constructor() {

      super();

      this.watchId = null; // unique ID for the geolocation watcher
      this.pusher = null; // variable for storing the Pusher instance
      this.user_channel = null; // the Pusher channel for the current user

      // bind the functions to the class
      this.onLogin = this.onLogin.bind(this);
      this.onLoginFound = this.onLoginFound.bind(this);
      this.onLogout = this.onLogout.bind(this);
      this.setUser = this.setUser.bind(this);
      this.setFriends = this.setFriends.bind(this);
      this.toggleLocationSharing = this.toggleLocationSharing.bind(this);
      this.onViewLocation = this.onViewLocation.bind(this);

      this.state = {
        is_loggedin: false, // whether the user is currently logged in or not
        is_location_shared: false, // whether the user is currently sharing their location or not
        user: null, // data for the currently logged in user
        friends: null, // data for the user's friends
        subscribed_to: null, // the Facbook user ID of the user's friend whose location is currently being viewed
        subscribed_friends_count: 0 // number of friends currently subscribed to the user
      };

    }

The onLogin() function is executed when the user has logged in with Facebook. Some of the user’s data such as the ID, access token and name are passed in as an argument to this function. It is then used to set the user’s and friends’ data on the state using two functions:

    onLogin(login_data) {
      this.setUser(login_data);
      this.setFriends(login_data.credentials.token);
    }

The onLoginFound() function is executed if an existing Facebook session is already present. The arguments passed in to this function are limited so we have to make a separate API request to get the user’s name:

    onLoginFound(data) {

      let token = data.credentials.token;

      fetch(`https://graph.facebook.com/me?access_token=${token}`)
        .then((response) => response.json())
        .then((responseJson) => {

          let login_data = {
            profile: {
              id: responseJson.id,
              name: responseJson.name
            },
            credentials: {
              token: token
            }
          };

          this.setUser(login_data);
        })
        .catch((error) => {
          console.log('something went wrong', error);
        });

      this.setFriends(token);

    }

Here’s the function for setting the data for the current user. All it does is format the login data returned by the Facebook API and set it on the state:

    setUser(login_data) {

      let user_id = login_data.profile.id;
      this.setState({
        is_loggedin: true,
        user: {
          id: user_id,
          access_token: login_data.credentials.token,
          name: login_data.profile.name,
          photo: `https://graph.facebook.com/${user_id}/picture?width=100` // the user's profile picture
        }
      });

    }

The setFriends() function makes a request to the Facebook API to get the array of the user’s friends:

    setFriends(token) {
      fetch(`https://graph.facebook.com/me/friends?access_token=${token}`)
        .then((response) => response.json())
        .then((responseJson) => {
          this.setState({
            friends: responseJson.data
          });
        })
        .catch((error) => {
          console.log('something went wrong', error);
        });
    }

Once the user logs out, destroying the session data is already taken care of by the Facebook login package. So all we have to do is unset all the user data that we’ve set earlier:

    onLogout() {
      this.setState({
        is_loggedin: false,
        user: null, 
        friends: null,
        is_subscribed_to: null
      });
    }

Next, initialize Pusher. Be sure to replace the placeholder values with your Pusher app details. We’re also passing in an auth paramater. This is the request data that we were checking earlier in the server code. Simply pass in the same unique string that you’ve used earlier when you added the secret:

    componentWillMount() {
      this.pusher = new Pusher('YOUR PUSHER APP ID', {
        authEndpoint: 'YOUR AUTH SERVER AUTH ENDPOINT',
        cluster: 'YOUR APP CLUSTER',
        encrypted: true,
        auth: {
          params: {
            app_key: 'YOUR UNIQUE KEY', // <-- should be the same as the unique key you added as a secret using now
          }
        }
      });

      // add code for listening for the unsubscribe event

    }

Next, we need a way to unsubscribe from a friend’s channel when the current user is no longer viewing their location on a map. That happens when the user goes back from the map page to the index page. The React Navigation library doesn’t really provide a way to listen for the event when the back button is tapped. That’s why we need a way to emulate that behavior. I’ll let you figure out your own solution. So feel free to skip the following paragraph if you want.

The solution I came up with is to use the DeviceEventEmitter module. Add a listener for the unsubscribe event, and once this is triggered, unsubscribe from the friend’s channel. The event is triggered from the map page when the user goes back to the index page:

    DeviceEventEmitter.addListener('unsubscribe', (e) => {
      let friend_id = this.state.subscribed_to;
      this.pusher.unsubscribe(`private-friend-${friend_id}`);
    });

The toggleLocationSharing() function is executed every time the user toggles the switch for sharing their location. If location sharing is enabled, we subscribe the user to their own channel. This allows them to listen for when one of their friends subscribes to their channel. When this happens, we begin watching the user’s current location and publish the data using Pusher. If the user decides to disable location sharing, we unsubscribe the user from their own channel and stop watching the location. This effectively stops the updating of location from their friends screens:

    toggleLocationSharing() {

      let is_location_shared = !this.state.is_location_shared;

      this.setState({
        is_location_shared: is_location_shared
      });

      let user_id = this.state.user.id;
      if(!is_location_shared){
        this.pusher.unsubscribe(`private-friend-${user_id}`); // disconnect from their own channel
        if(this.watchId){
          navigator.geolocation.clearWatch(this.watchId);
        }
      }else{
        this.user_channel = this.pusher.subscribe(`private-friend-${user_id}`);
        this.user_channel.bind('client-friend-subscribed', (friend_data) => {

          let friends_count = this.state.subscribed_friends_count + 1;
          this.setState({
            subscribed_friends_count: friends_count
          });

          if(friends_count == 1){ // only begin monitoring the location when the first subscriber subscribes
            this.watchId = navigator.geolocation.watchPosition(
              (position) => {
                var region = regionFrom(
                  position.coords.latitude,
                  position.coords.longitude,
                  position.coords.accuracy
                );
                this.user_channel.trigger('client-location-changed', region); // push the data to subscribers
              }
            );
          }
        });  

      }
    }

The onViewLocation() function is executed when the user taps on any friend on their friend list. This is where we subscribe to the friend’s channel so we can get updates whenever their location changes:

    onViewLocation(friend) {

      this.friend_channel = this.pusher.subscribe(`private-friend-${friend.id}`);
      this.friend_channel.bind('pusher:subscription_succeeded', () => {
        let username = this.state.user.name;
        this.friend_channel.trigger('client-friend-subscribed', {
          name: username
        });
      });

      this.setState({
        subscribed_to: friend.id
      });

      // add code for navigating to the map page
    }

Next, add the code for navigating to the map page. Pass in the name of the friend and the reference to the friend’s channel as navigation props. This allows those values to be accessed from the map page later on:

    const { navigate } = this.props.navigation;

    navigate('MapPage', {
      name: friend.name,
      friend_channel: this.friend_channel // pass the reference to the friend's channel
    });

Render the index page. This consists of the user’s profile, their friends list and the Facebook login or logout button:

    render() {

      return (
        <View style={styles.page_container}>
        {
          this.state.is_loggedin &&
          <View style={styles.container}>
          {
            this.state.user &&
            <View style={styles.profile_container}>
              <Profile
                profile_picture={this.state.user.photo}
                profile_name={this.state.user.name}
              />

              <Text>Share Location</Text>
              <Switch
                value={this.state.is_location_shared}
                onValueChange={this.toggleLocationSharing} />
            </View>
          }

          {
            this.state.friends &&
            <Friends
              friends={this.state.friends}
              onViewLocation={this.onViewLocation} />
          }
          </View>
        }

          <FBLogin
            permissions={["email", "user_friends"]}
            onLogin={this.onLogin}
            onLoginFound={this.onLoginFound}
            onLogout={this.onLogout}
            style={styles.button}
          />
        </View>
      );

    }

    // add the styles
    const styles = StyleSheet.create({
      page_container: {
        ...StyleSheet.absoluteFillObject,
        justifyContent: 'flex-end'
      },
      container: {
        flex: 1,
        padding: 20
      },
      profile_container: {
        flex: 1,
        alignItems: 'center',
        marginBottom: 50
      },
      button: {
        paddingBottom: 30,
        marginBottom: 20,
        alignSelf: 'center'
      }
    });

The code above is pretty self-explanatory so I won’t go into details what each line does.

Profile Component

The Profile component is used for displaying the user’s profile picture and name:

    import React, { Component } from 'react';
    import {
      StyleSheet,
      Text,
      View,
      Image
    } from 'react-native';

    import PropTypes from 'prop-types';

    class Profile extends Component<{}> {

      render() {

        return (
          <View style={styles.profile_container}>
            <Image
              resizeMode={"contain"}
              source={{uri: this.props.profile_picture}}
              style={styles.profile_photo}
            />
            <Text style={styles.profile_name}>{this.props.profile_name}</Text>
          </View>
        );

      }

    }

    const styles = StyleSheet.create({
      profile_container: {
        alignItems: 'center'
      },
      profile_photo: {
        height: 100,
        width: 100
      },
      profile_name: {
        fontWeight: 'bold',
        fontSize: 18
      }
    });

    // specify the required props
    Profile.propTypes = {
      profile_picture: PropTypes.string.isRequired,
      profile_name: PropTypes.string.isRequired
    };

    export default Profile;

Friends Component

The Friends component is used for rendering the list of friends:

    import React, { Component } from 'react';
    import {
      StyleSheet,
      Text,
      View,
      Image,
      TouchableHighlight
    } from 'react-native';

    import PropTypes from 'prop-types';

    class Friends extends Component<{}> {

      renderFriends() {
        return this.props.friends.map((friend, index) => {

          let profile_picture = `https://graph.facebook.com/${friend.id}/picture?width=50`;
          return (
            <TouchableHighlight
              key={index}
              onPress={this.props.onViewLocation.bind(this, friend)}
              underlayColor={"#CCC"}>

                <View style={styles.friend_row}>
                  <Image
                    resizeMode={"contain"}
                    source={{uri: profile_picture}}
                    style={styles.profile_photo}
                  />
                  <Text style={styles.friend_name}>{friend.name}</Text>
                </View>

            </TouchableHighlight>
          );
        });
      }

      render() {

        return (
          <View style={styles.friends_container}>
            <Text style={styles.friends_header_text}>View Friend Location</Text>
            {this.renderFriends.call(this)}
          </View>
        );

      }
    }

    // add the styles
    const styles = StyleSheet.create({
      friends_container: {
        flex: 2
      },
      friends_header_text: {
        fontSize: 18,
        fontWeight: 'bold'
      },
      friend_row: {
        flexDirection: 'row',
        alignItems: 'center',
        padding: 10
      },
      profile_photo: {
        width: 50,
        height: 50,
        marginRight: 20
      },
      friend_name: {
        fontSize: 15
      }
    });

    // specify the required props
    Friends.propTypes = {
      friends: PropTypes.arrayOf(
        PropTypes.shape({
          id: PropTypes.string.isRequired,
          name: PropTypes.string.isRequired
        })
      ),
      onViewLocation: PropTypes.func.isRequired
    };

    export default Friends;

Region Helper

Earlier, we’ve used a function called regionFrom but we haven’t really created it yet. So go ahead and create a src/helpers.js file and add the following:

    export function regionFrom(lat, lon, accuracy) {
      const oneDegreeOfLongitudeInMeters = 111.32 * 1000;
      const circumference = (40075 / 360) * 1000;

      const latDelta = accuracy * (1 / (Math.cos(lat) * circumference));
      const lonDelta = (accuracy / oneDegreeOfLongitudeInMeters);

      return {
        latitude: lat,
        longitude: lon,
        latitudeDelta: Math.max(0, latDelta),
        longitudeDelta: Math.max(0, lonDelta)
      };
    } 

This function is used for getting the latitude and longitude delta values needed by the React Native Maps library to display a map.

Map Page

Now we move over to the map page. Create a src/map_page.js file and add the following:

    import React, { Component } from 'react';
    import {
      StyleSheet,
      Text,
      View,
      DeviceEventEmitter
    } from 'react-native';

    import Map from './map';

    import { regionFrom } from '../helpers';

    // add code for creating the component

Create the component, and set the page title based on the parameters passed from the index page:

    export default class MapPage extends Component<{}> {

      static navigationOptions = ({navigation}) => ({
        title: `${navigation.state.params.name}'s Location`,
      });

     // add constructor code 
    }

Set a default location in the constructor so that a map is still displayed even if the user is not sharing their location:

    constructor() {
      super();

      // set default location
      let region = {
        "latitude": 35.4625901,
        "longitude": 138.65437569999995,
        "latitudeDelta": 0,
        "longitudeDelta": 0
      };

      this.state = {
        region
      }
    }

When the user taps on the back button, componentWillUnmount() is triggered as the component goes out of view. So this is the perfect time to trigger the unsubscribe event to let the index page know that the user has stopped viewing their friends location.

    componentWillUnmount() {
      DeviceEventEmitter.emit('unsubscribe',  {
        unsubscribe: true
      });
    }

When the component is mounted, we want to start listening for when the location changes so we can update the map accordingly:

    componentDidMount() {

      const { state } = this.props.navigation;
      state.params.friend_channel.bind('client-location-changed', (data) => {
        this.setState({
          region: data
        });
      });

    }

The render() method simply outputs the Map component:

    render() {

      return (
        <View style={styles.map_container}>
        {
          this.state.region &&
          <Map region={this.state.region} />
        }
        </View>
      );

    }

Add the styles:

    const styles = StyleSheet.create({
      map_container: {
        ...StyleSheet.absoluteFillObject,
        justifyContent: 'flex-end'
      }
    });

Map Component

Lastly, there’s the Map component which is used to actually render the Google Map. This uses the React Native Maps package that we installed earlier. There are only two components that you need in order to make it work: MapView and MapView.Marker. MapView is used to render the map, and MapView.Marker is used to render the marker:

    import React, { Component } from 'react';
    import {
      StyleSheet,
      View
    } from 'react-native';

    import MapView from 'react-native-maps';
    import PropTypes from 'prop-types';

    class Map extends Component<{}> {

      render() {

        return (
          <View style={styles.map_container}>
            {
            this.props.region &&
              <MapView
                style={styles.map}
                region={this.props.region}
              >
                <MapView.Marker
                  coordinate={{
                    latitude: this.props.region.latitude,
                    longitude: this.props.region.longitude}}
                />
              </MapView>
            }
          </View>
        );

      }

    }

    // add the styles
    const styles = StyleSheet.create({
      map_container: {
        ...StyleSheet.absoluteFillObject,
        justifyContent: 'flex-end'
      },
      map: {
        ...StyleSheet.absoluteFillObject,
      },
    });

    // specify the required props
    Map.propTypes = {
      region: PropTypes.shape({
        latitude: PropTypes.number.isRequired,
        longitude: PropTypes.number.isRequired,
        latitudeDelta: PropTypes.number.isRequired,
        longitudeDelta: PropTypes.number.isRequired
      })
    };

    export default Map;

Running the App

You only need one device and one emulator in order to test the app. First, run the app on your device by executing react-native run-android. Once the app is running, disconnect the device and open a Genymotion virtual device. Execute the same command again to run the app on the virtual device. Don’t forget to add another Facebook user, aside from your own Facebook account as a tester or developer under the Facebook app settings. You can do that by clicking on the Roles tab and searching for the user in there. Only Facebook users that are added in the app settings can login. This is because the Facebook app is still unpublished.

Genymotion has a built-in functionality for spoofing the GPS coordinates. This will trigger the geolocation functionality in the app everytime the location changes (either by pointing the marker on a different location on the map or searching for another place). That’s why it’s best to use Genymotion for testing the user who is broadcasting their location. If you’re going to follow this route, be sure to check out the documentation on how to install Google Services on Genymotion since the Google Map functionality uses Google Services.

If you don’t have any device to test on, you can use Genymotion and the Pusher debug console to test the app. All you have to do is figure out the Facebook user ID’s of the two users you’re using for testing. You can do that by using this tool. Login with your Facebook account on Genymotion then click on one of the other accounts. You can then emulate the location update by manually entering the coordinates on the debug console. You can access the debug console from your Pusher app’s dashboard:

You can use the following as initial values:

  • channel name: private-friend-YOUR-ACCOUNTS-FB-ID
  • event: client-location-changed
  • data: you can use the following data for testing:
    {
      "latitude": 16.6105538,
      "longitude": 120.31429539999999,
      "latitudeDelta": 0,
      "longitudeDelta": 0
    }

Send the event once that’s done. Sending the event should update the map on the app. You can use a service such as latlong.net to come up with the coordinates of different places.

Suggestions for Improvement

If you want to improve the app, here are some ideas on what you can add:
– The number of friends that are currently viewing the user’s location doesn’t actually get updated when someone disconnects from the user’s channel. You can add a listener for when someone disconnects, so that you can update the value as well.
– The current user doesn’t actually know who are the people that are currently subscribed to their location. For this you can use an alert dialog everytime someone subscribes to the channel. The client-friend-subscribed event has already been laid out for this purpose. You can even take the idea further by making use of Presence channels. This comes with an additional feature that allows you to keep track of the people that are subscribed to a specific channel.
– Add notifications to inform the subscribed users for when the user they’re subscribed to disables location sharing.

Conclusion

That’s it! In this tutorial you’ve learned how to create a location-sharing app which uses React Native’s built-in Geolocation library and Pusher to broadcast the data to the user’s friends. You can check out the project’s complete souce code in its Github repo.