In this tutorial, we’ll create a ride-booking app with React Native and Pusher. The app that we’ll create will be similar to popular ride-booking apps like Uber, Lyft or Grab.
React Native will be used to create an Android app for both the driver and the passenger. Pusher will be used for real-time communication between the two.

What You’ll Create

Just like any other ride-booking app out there, there will be a driver app and a passenger app. The passenger app will be used for booking a ride, and the driver app simply receives any request that comes from the passenger app. For consistency purposes, we’ll just refer to the app as “grabClone”.

App Flow

The clone that we’re going to create will pretty much have the same flow as any ride booking app out there: passenger books a ride → app looks for a driver → driver accepts the request → driver picks up passenger → driver drives to destination → passenger pays the driver.

Here I just want to show you how this process would look like inside the app. That way you’ll have a clear picture of what you’re going to create.

The app determines the user’s location and shows it in a map (note: GPS needs to be enabled at this point).

From the passenger app, the user clicks on “Book a Ride”.

A modal will open that will allow the passenger to pick the place where they want to go.

The app asks the passenger to confirm their destination.

Once confirmed, the app sends a request to the driver app to pick up the passenger. A loading animation is shown while the app is waiting for a driver to accept the request.

The driver app receives the request. From here, the driver can either accept or reject the request.

Once the driver accepts the request, the driver’s details are shown in the passenger app.

The passenger app shows the current location of the driver on the map.

Once the driver is within 50 meters of the passenger’s location, they will see an alert saying that the driver is near.

Once the driver is within 20 meters of the passenger’s location, the driver app sends a message to the passenger app that the driver is almost there.

After picking up the passenger, the driver drives to their destination.

Once the driver is within 20 meters of their destination, the driver app sends a message to the passenger app that they’re very near their destination.

At this point, the ride ends and the passenger can book another ride. The driver is also free to accept any incoming ride request.

Install Android Studio – you don’t really need Android Studio, but it comes with Android SDK which is the one we need. Google also no longer offers a separate download for it.

Install React Native – the method I recommend for this is building projects the native way. When you’re on the React Native website, click on the “Building Projects with Native Code” tab and follow the instructions in there. The expo client is great for quickly prototyping apps but it doesn’t really offer a quick way for us to test the Geolocation features that we need for this app.

Genymotion – for testing the driver app. We’re using this instead of the default Android emulator because it comes with a GPS simulation tool that allows us to search for a specific location and have it used as the location of the emulated device. It uses Google maps as the interface and you can move the marker as well. This allows us to simulate a moving vehicle. Once Genymotion is installed, you need to login to your account in order to add a device. For me I’ve installed Google Nexus 5x for testing.

Android Device – this will be used for testing the passenger app. Be sure to check the Android version of your phone. If it’s something as low as 4.2 then you’ll need to install additional packages via the Android SDK Manager. This is because, by default, React Native targets API version 23 or higher. That means the Android version of your phone needs to be version 6.0 at the very least or the app won’t run. If you have installed Android Studio, you can access the SDK Manager by opening Android Studio → click “Configure” → select “SDK Manager“. Then under the “SDK Platforms”, check the Android versions that you want to support.

While you’re there, click on the “SDK Tools” and make sure that you also have the same tools installed as mine:

An extra computer – this is optional. I just included it here because React Native can only run the app on a single device or emulator at a time. Thus, you need to do some extra work in order to run the two apps as you’ll see later on.

Creating the Auth Server

Now it’s time to get our hands dirty. First, let’s work on the auth server. This is required because we will be sending client events from the app, client events requires the Pusher channel to be private, and private channels have restricted access. This is where the auth server comes in. It serves as a way for Pusher to know if a user that’s trying to connect is indeed a registered user of the app.

I’m no longer going to go into detail what the code above does since its already explained in the docs for Authenticating Users.
To keep things simple, I haven’t actually added the code to check if a user really exists in a database. You can do that in the /pusher/auth endpoint by checking if a username exists. Here’s an example:

This allows you to access your Pusher app settings from inside the server like so:

process.env.APP_ID

The deploy URL that now.sh returns is the URL that you’ll use later on to connect the app to the auth server.

Creating the Driver App

Now you’re ready to start creating the driver app.

First, create a new React Native app:

react-native init grabDriver

Installing the Dependencies

Once that’s done, navigate inside the grabDriver directory and install the libraries that we’ll need. This includes pusher-js for working with Pusher, React Native Maps for displaying a map, and React Native Geocoding for reverse-geocoding coordinates to the actual name of a place:

npm install --save pusher-js react-native-maps react-native-geocoding

Once all the libraries are installed, React Native Maps needs some additional steps in order for it to work. First is linking the project resources:

Also make sure that it’s targeting the same API version as the device you installed with Genymotion. As I’ve said earlier, if its version 23 or above you won’t really need to do anything, but if its lower than that then it has to be exact for the app to work.

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="23" />

Lastly, since we’ll be primarily using Genymotion for testing the driver app, you need to follow the instructions here. In case the link goes broken, here’s what you need to do:

Drag & Drop the zip installer in a new Genymotion virtual device (2.7.2 and above only).

Follow the pop-up instructions.

We need to do this because the React Native Maps library primarily uses Google Maps. We need to add Google Play Services in order for it to work. Unlike most Android phones which already comes with this installed, Genymotion doesn’t have it by default due to intellectual property reasons. Thus, we need to manually install it.

If you’re reading this sometime after it was published, be sure to check out the Installation docs to make sure you’re not missing anything.

Coding the Driver App

Now you’re ready to start coding the app. Start by opening the index.android.js file and replace the default code with the following:

These functions are used for getting the latitude and longitude delta values needed by the React Native Maps library to display a map. The other function (getLatLonDiffInMeters) is used for determining the distance in meters between two coordinates. Later on, this will allow us to inform the user’s whether they’re already near each other or when they’re near their destination.

Inside the constructor, initialize the variables that will be used throughout the app:

constructor() {
super();
this.available_drivers_channel = null; // this is where passengers will send a request to any available driver
this.ride_channel = null; // the channel used for communicating the current location
// for a specific ride. Channel name is the username of the passenger
this.pusher = null; // the pusher client
}
// next: add code for connecting to pusher

Before the component is mounted, connect to the auth server that you created earlier. Be sure to replace the values for the pusher key, authEndpoint and cluster.

Now that you’ve connected to the auth server, you can now start listening for requests coming from the passenger app. The first step is to subscribe to a private channel. This channel is where all passengers and drivers subscribe to. In this case, its used by drivers to listen for ride requests. It needs to be a private channel because client events can only be triggered on private and presence channels due to security reasons. You know that it’s a private channel because of the private- prefix.

Next, listen to the client-driver-request event. You know that this is a client event because of the client- prefix. Client events don’t need server intervention in order to work, the messages are sent directly to from client to client. That’s the reason why we need an auth server to make sure all the users that are trying to connect are real users of the app.

Going back to the code, we listen for client events by calling the bind method on the channel that we subscribed to and passing in the name of the event as the first argument. The second argument is the function that you want to execute once this event is triggered from another client (from anyone using the passenger app to request a ride). In the code below, we show an alert message asking the driver if they want to accept the passenger. Note that the app assumes that there can only be one passenger at any single time.

Once the driver agrees to pick up the passenger, we subscribe to their private channel. This channel is reserved only for communication between the driver and the passenger, that’s why we’re using the unique passenger username as part of the channel’s name.

Not unlike the available-drivers channel, we’ll need to listen for when the subscription actually succeeded (pusher:subscription_succeeded) before we do anything else. This is because we’re going to immediately trigger a client event to be sent to the passenger. This event (client-driver-response) is a handshake event to let the passenger know that the driver they sent their request to is still available. If the passenger still hasn’t gotten a ride at that time, the passenger app triggers the same event to let the driver know that they’re still available for picking up. At this point, we update the state so that the UI changes accordingly.

Next, we use the Geocoding library to determine the name of the place where the driver is currently at. Behind the scenes, this uses the Google Geocoding API and it usually returns the street name. Once we get a response back, we trigger the found-driver event to let the passenger know that the app has found a driver for them. This contains driver info such as the name and the current location.

Once the component is mounted, we use React Native’s Geolocation API to watch for location updates. The function that you pass to the watchPosition function gets executed everytime the location changes.

componentDidMount() {
this.watchId = navigator.geolocation.watchPosition(
(position) => {
var region = regionFrom(
position.coords.latitude,
position.coords.longitude,
position.coords.accuracy
);
// update the UI
this.setState({
region: region,
accuracy: position.coords.accuracy
});
if(this.state.has_passenger && this.state.passenger){
// next: add code for sending driver's current location to passenger
}
},
(error) => this.setState({ error: error.message }),
{
enableHighAccuracy: true, // allows you to get the most accurate location
timeout: 20000, // (milliseconds) in which the app has to wait for location before it throws an error
maximumAge: 1000, // (milliseconds) if a previous location exists in the cache, how old for it to be considered acceptable
distanceFilter: 10 // (meters) how many meters the user has to move before a location update is triggered
},
);
}

Next, send the driver’s current location to the passenger. This will update the UI on the passenger app to show the current location of the driver. You’ll see how the passenger app binds to this event later on when we move on to coding the passenger app.

Next, we want to inform both the passenger and the driver that they’re already near each other. For that, we use the getLatLonDiffInMeters function from the helpers.js file in order to determine the number of meters between the passenger and the driver. Since the driver already received the passenger location when they accepted the request, it’s only a matter of getting the current location of the driver and passing it to the getLanLonDiffInMeters function to get the difference in meters. From there, we simply inform the driver or the passenger based on the number of meters. Later on you’ll see how these events are received in the passenger app.

At this point, we assume that the driver has picked up the passenger and that they’re now heading to their destination. So this time we get the distance between the current location and the drop-off point. Once they’re 20 meters to the drop-off point, the driver app sends a message to the passenger that they’re very close to their destination. Once that’s done, we assume that the passenger will get off in a few seconds. So we unbind the events that we’re listening to and unsubscribe from the passenger’s private channel. This effectively cuts the connection between the driver and passenger app. The only connection that stays open is the available-drivers channel.

Since we’ve installed the same libraries, you can go back to the section where we did some additional configuration in order for the library to work. Come back here once you’ve done those.

Next, the Google Place Picker also needs some additional configuration for it to work. First, open the android/app/src/main/java/com/grabClone/MainApplication.java file and add the following below the last import:

import com.reactlibrary.RNGooglePlacePickerPackage;

Add the library that you just imported under the getPackages() function. While you’re there, also make sure that the MapsPackage() is listed as well.

export default class App extends Component {
state = {
location: null, // current location of the passenger
error: null, // for storing errors
has_ride: false, // whether the passenger already has a driver which accepted their request
destination: null, // for storing the destination / dropoff info
driver: null, // the driver info
origin: null, // for storing the location where the passenger booked a ride
is_searching: false, // if the app is currently searching for a driver
has_ridden: false // if the passenger has already been picked up by the driver
};
// next: add constructor code
}

To keep things simple, we declare the username of the passenger in the constructor. We also initialize the Pusher channels:

constructor() {
super();
this.username = 'wernancheta'; // the unique username of the passenger
this.available_drivers_channel = null; // the pusher channel where all drivers and passengers are subscribed to
this.user_ride_channel = null; // the pusher channel exclusive to the passenger and driver in a given ride
this.bookRide = this.bookRide.bind(this); // bind the function for booking a ride
}
// next: add bookRide() function

The bookRide() function gets executed when the user taps on the “Book Ride” button. This opens a place picker which allows the user to pick their destination. Once a location is picked, the app sends a ride request to all drivers. As you have seen in the driver app earlier, this triggers an alert to show in the driver app which asks if the driver wants to accept the request or not. At this point the loader will keep on spinning until a driver accepts the request.

The _setCurrentLocation() function gets the passenger’s current location. Note that here we’re using getCurrentPosition() as opposed to watchPosition() which we used in the driver app earlier. The only difference between the two is that getCurrentPosition() only gets the location once.

When the component mounts, we want to set the current location of the passenger, connect to the auth server and subscribe to the two channels: available drivers and the passenger’s private channel for communicating only with the driver’s where the ride request was sent to.

Next, add the code for listening to the handshake response by the driver. This is being sent from the driver app when the driver accepts a ride request. This allows us to make sure that the passenger is still looking for a ride. If the passenger responds with “yes” then that’s the only time that the driver sends their information.

Next is the event that is triggered on specific instances. It’s main purpose is to send updates to the passenger regarding the location of the driver (near_pickup ) and also when they’re already near the drop-off location (near_dropoff).

this.user_ride_channel.bind('client-driver-message', (data) => {
if(data.type == 'near_pickup'){ // the driver is very near the pickup location
// remove passenger marker since we assume that the passenger has rode the vehicle at this point
this.setState({
has_ridden: true
});
}
if(data.type == 'near_dropoff'){ // they're near the dropoff location
this._setCurrentLocation(); // assume that the ride is over, so reset the UI to the current location of the passenger
}
// display the message sent from the driver app
Alert.alert(
data.title,
data.msg,
[
{
text: 'Aye sir!'
},
],
{ cancelable: false }
);
});
// next: render the UI

The UI composed of the loading spinner (only visible when the app is searching for a driver), the header, the button for booking a ride, the passenger location (origin) and their destination, and the map which initially displays the current location of the user and then displays the current location of the driver once a ride has been booked.

Running the App

Now you’re ready to run the app. As I mentioned in the Prerequisites section earlier, you’re going to optionally need two machines, one for running each of the app. This will allow you to enable logging (console.log) for both. But if you have only one machine then you have to run them in particular order: passenger app first and then driver app.

Go ahead and connect your Android device to your computer and run the following command:

react-native run-android

This will compile, install and run the app on your device. Once its running, terminate the watcher and disconnect your device from the computer.

Next, open Genymotion and launch the device that you installed earlier. This time, run the driver app. Once the app runs you’ll see a blank screen. This is normal because the app needs a location in order to render something. You can do that by clicking on “GPS” located on the upper right-side of the emulator UI then enable GPS.

You can also click on the map button and select a specific location if you want:

Once you’ve selected a location, the map UI in the app should show the same location that you selected.

Next, you can now follow the steps on the App Flow section earlier. Note that you can emulate a moving vehicle by clicking around the Genymotion Map UI. If a passenger has already booked a ride and the driver has accepted the request, it should start updating both the passenger app and the driver app of the current location of the driver.

If you’re using two machines, then you can simply run react-native run-android on both. One should be connected to your device and the other should have the Genymotion emulator open.

Conclusion

That’s it! In this tutorial you’ve learned how to make use of Pusher to create a ride-booking app. As you have seen, the app that you’ve built is pretty bare-bones. We’ve only stick to building the most important parts of a ride-booking app. If you want you can add more features to the app and maybe use it on your own projects. You can find the source code used in this app on its Github repo.