How to Develop a Location-based Application Using React Native

How does Uber always know the pickup location? Or how can Tinder find dates within a two-mile radius from you? It’s simple – you allowed them to know your location.

Location-based apps use customers’ locations to function and control different features. From pizza delivery and taxi to Find My iPhone and telling the bus schedule, location-based applications have been helping us out with our everyday tasks.

Location might be either the primary function, like in Uber, or auxiliary, like in Facebook – it often always tells you when there is an upcoming event near you. Whether primary function or not, location helps improve user experience.

Develop a Location-based Application

In this article, we will tell you about the main components of location-based apps and how to develop one using the React Native framework. First, we will study what React Native is and compare it to native app development. Then we will share approaches to gathering and displaying the location in an app. And finally, we will examine the design challenges and the ways to solve them.

Tools For Location-Based Service Development: Native vs. React Native

Here is a brief description of React Native. It is an open source JavaScript framework created by Facebook that allows developers to create cross-platform apps with their native behavior.

What is behavior here? Let me explain. iOS and Android are different – they look different, their buttons are different, the common gestures are different. Developing an app for iOS and Android would require building two separate apps. It used to be a time-consuming process, but now we can write single code and it will work well on both platforms.

This helps businesses offer their app to both iOS and Android users, which increases the potential customer base. React Native is a popular choice for new companies that cannot afford building two separate apps or are unsure whether their audience uses iOS or Android. Taking into account that the cross-platform market is likely to grow to $80 billion by 2020, it makes perfect sense for many businesses to opt for React Native.

Now we are moving to the pros and cons of React Native. It is not an almighty and all-powerful framework, but there are definite cases when you should use it.

React Native Pros

  • Cross-platform. Instead of writing separate code for each platform, you can use the same for both iOS and Android. You also shall not design different UI and UX.
  • High performance. React Native uses native controls and modules. It interacts with the native iOS and Android components and renders code to native API. Native API is the core here – by using a separate thread from UI, it increases the performance of apps.
  • Open-source. The React Native community is growing fast, and so is the number of ready components. This lets developers share their experience, improve the framework, find solutions to existing bugs, and therefore make the development process faster.
  • It saves money. As a result of the three previous points, using React Native saves you money. It is faster than building two separate apps and it takes less time on testing and releasing an MVP.

However, there are a few reasons when you might not want to use React Native.
They include:

  • You do not need a cross-platform app. If you know what OS your audience uses, I suggest you use native development. First, the app will be tailored to fit the specifics of the chosen OS, and second, you will be able to use platform-specific features.
  • You need access to more APIs than React Native can offer. The framework does not support all native platform APIs. One core reason why many prefer native code is independency from external factories and third-party services because everything can be accessed through native frameworks.

speaking of react native

How to gather and display user location

In this part, we will tell you about the ways to gather and display the location data. The choice usually depends on the specifics on the app being developed.

Gathering location data

We will point out three ways to gather user location. This is a generic overview for you to understand the cases when to opt for each and differences between them.

Use React Native API

There is a native JavaScript API for detecting the geolocation of a device. It is simple to install and use, but there are some drawbacks – it works only when the app is running and does not give information about the location provider (3G, Wi-Fi, GPS).

react-native-background-geolocation

It is a package that can specify the location of a device from 0 to 1000 meters (0.6 miles). Such precision requires higher battery consumption but on the other hand, you can configure how often to track the location. This package lets you integrate with SQLite so that you can store the recorded location data on the mobile device and then sync it to your database via HTTP.

import { NativeModules, DeviceEventEmitter, PermissionsAndroid } from 'react-native'  
import Config from 'react-native-config'  
import get from 'lodash/get'  
const { GeoLocation } = NativeModules

class BackgroundGeoLocation {  
  constructor(token, user_id) {
    this.state = null
  }
  start(dispatch, nextState) {
    this.dispatch = dispatch
    const token = get(nextState, 'session.data.token')
    const user_id = get(nextState, 'user.data.user_id')
    const id = get(nextState, 'user.data.id')
    this.state = {
      user_id,
      token,
    }

    return PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION)
      .then(is_granted => is_granted === PermissionsAndroid.RESULTS.GRANTED
        ? is_granted
        : PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
        ])
      )
      .then(_ => PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION))
      .then(is_granted => is_granted === PermissionsAndroid.RESULTS.GRANTED ? true : new Error())
      .then(_ => setTimeout(() => GeoLocation.startService(token, user_id, id, `${Config.API_URL}/live/car-tracking/gps-pos/`), 300))
      .catch(e => console.log(e))
  }
  stop() {
    return GeoLocation.stopService()
      .then(_ => console.log(_))
  }

  handleLocationChange(geo) {
    console.log(geo)
  }
}

export default BackgroundGeoLocation

Since it is a package, you need to maintain and update it regularly. Luckily, its creator offers support via Github. This package is free for iOS but costs $300 for Android for one app.

Bridge native code to JavaScript API

To solve the problem with the background tracking when using the native JavaScript API, you can write native code that will start a foreground service in a separate thread. We used this solution when developing our product partly because React Native makes it easy to bridge native code to React Native components.

package com.djangostars.azyan;

import android.app.Notification;  
import android.app.NotificationChannel;  
import android.app.NotificationManager;  
import android.content.Context;  
import android.content.Intent;  
import android.content.pm.PackageManager;  
import android.location.Criteria;  
import android.location.Location;  
import android.location.LocationManager;  
import android.os.Build;  
import android.support.v4.content.ContextCompat;

import com.facebook.react.bridge.Arguments;  
import com.facebook.react.bridge.Promise;  
import com.facebook.react.bridge.ReactApplicationContext;  
import com.facebook.react.bridge.ReactContextBaseJavaModule;  
import com.facebook.react.bridge.ReactMethod;  
import com.facebook.react.bridge.WritableMap;  
import com.facebook.react.bridge.WritableNativeMap;


/**
 * Created by AGulchenko on 5/7/18.
 */

public class GeoLocationModule extends ReactContextBaseJavaModule {  
    public static final String CHANNEL_ID = "ExampleService_Channel";
    public GeoLocationModule(ReactApplicationContext reactContext) {
        super(reactContext);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,"testName", NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = reactContext.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    @Override
    public String getName() {
        return "GeoLocation";
    }

    @ReactMethod
    public void startService(String token, String user_id, String id, String url_string, Promise promise) {
        WritableMap result = Arguments.createMap();
        result.putString("ststus", "success");
        try {
            Intent serviceIntent = new Intent(getReactApplicationContext(), GeoLocationService.class);
            serviceIntent.putExtra("token", token);
            serviceIntent.putExtra("user_id", user_id);
            serviceIntent.putExtra("id", id);
            serviceIntent.putExtra("url_string", url_string);
            getReactApplicationContext().startService(serviceIntent);
            promise.resolve(result);
        } catch (Exception e) {
            e.printStackTrace();
            promise.reject("rrrrr",e);
            return;
        }

    }

    @ReactMethod
    public void stopService(Promise promise) {
        String result = "Success";
        try {
            Intent serviceIntent = new Intent(getReactApplicationContext(), GeoLocationService.class);
            getReactApplicationContext().stopService(serviceIntent);
        } catch (Exception e) {
            promise.reject(e);
            return;
        }
        promise.resolve(result);
    }

    @ReactMethod
    public void getLocation( Promise promise) {
        WritableMap res = Arguments.createMap();
        try {
            LocationManager locationManager = null;

            locationManager = (LocationManager) this.getReactApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            int permissionCheck = ContextCompat.checkSelfPermission(this.getReactApplicationContext(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                Criteria criteria = new Criteria();
                String bestProvider = locationManager.getBestProvider(criteria, false);
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if(location != null) {
                    res.putDouble("latitude", location.getLatitude());
                    res.putDouble("longitude", location.getLongitude());
                    promise.resolve(res);
                }

            }
        } catch (Exception e) {
            promise.reject(e);
            return;
        }
    }
}

Permission To Access Location Data

Despite having to upgrade React Native with native code, we decided to keep on using React Native for its ease with getting permission for using location info. Here is why it could cause troubles.

Different platforms may require permission to access the location data on different steps: on iOS, the permission is requested the first time you open an app; on Android, it is requested upon the download. If using native code, we would need to take it into account. But React Native simplifies this process using the check access to location data module. It verifies the access to location data without triggering the permission alert.

Displaying Location

If not approached carefully, the location data may be displayed inaccurately. The device gathers data about its current location from three sources: GPS, Wi-Fi and cellular network (3G, 4G). Since Wi-Fi and cellular data is more accurate than GPS (signal from the device to satellite may be distorted), the device is constantly checking whether there is Internet connection. If so, the location data comes from it. If not, it uses GPS. When getting inaccurate data, we may observe zigzags on a map rather than straight lines. It looks something like this:

location-based 2

To solve this problem, we suggest you use Fused Location Client by Google. It allows to set the time and distance at which the location data is updated; e.g., update the data every 100 meters, every 5 seconds. You will get rid of the noisy data as this API matches all device locations to roads and sidewalks. However, if the device is somewhere in the Pacific or the Alps, it may not be that effective.

location-based 3

Fused Location Client allows one not to display certain locations in which accuracy is lower than a set threshold. Such an adjustment results in the noise reduction and more accurate display of the location.

A Few Words About Design

In this brief part, we will study the obstacles that usually arise when developing a location-based application and how React Native overcomes those obstacles.

React Native allows simple approaches to displaying maps. React Native UI components for Material Design let developers do the job faster and with less efforts. We at Django Stars used Material Design to create a Google Maps wrapper and then React Native would adjust them to the specifics of each platform.

Infinite List is a React Native feature that creates an endless list of search results. In Uber, the endless list appears when you start typing the destination point. If you start typing 3 Ave, it will show all Third Avenues around you. The list is not actually endless; it is just that it loads more search results as users scroll down.

<FlatList  
        data={get(props, 'order.data.items', [])}
        renderItem={listItem}
        keyExtractor={({ id }) => id}
        style={style.list}
      />

function listItem({ item: { quantity, name } }) {  
  return (
    <View style={style.main}>
      <Text style={[style.count, style.listItemText]}>{quantity}</Text>
      <Text style={[style.listItemText, style.name]}>{name}</Text>
    </View>
  )
}

In React Native, there is a ready interface component, Flat List, that has a fixed header, footer, and delimiters. Creating such lists from scratch is a time-consuming activity, so React Native is the right choice for this functionality.

Bottom Line

We have studied why React Native might be the right choice if you are going to build a location-based application. We have also identified the main methods to gather and display the location on a device.

We have listed the main advantages of developing an app using React Native. If most of them are true for you, we suggest you do deeper research on the technology and its possibilities.

We now encourage you to pay more attention to the apps that are using device location. You may be surprised that most apps you know ask to allow access to your location. For many businesses, it is crucial to know your location to deliver the best service. Google, Facebook, Airbnb, Amazon – all of them use location as a basis for some of their functionality: where to search, where to stay, where to ship. If used properly, location data allows to make the service more user-oriented and efficient.

Comments