04 – A basic React Native app

In this Section, we provide an Android and iOS step-by-step guide to build your first Situm app using React Native. For more advanced use cases, take a look at our React Native sample app and at the Plugin Method Reference.

Pre-requisites: Installing React Native #

First, you need to setup react-native development environment. To get started please follow instructions under section React Native CLI Quickstart on this guide and finally execute the react-native cli:

$ npx react-native init my_indoor_location_app

Installing Situm SDK for React Native #

Then, you may install Situm SDK for React Native by using npm or yarn (plus some dependencies that are needed):

# You may use yarn
$ yarn add @situm/react-native react-native-permissions react-native-webview

# or you may also use npm
$ npm install --save @situm/react-native react-native-permissions react-native-webview

Please note! We are using Cocoapods in order to manage iOS dependencies, which means you might need to run pod repo update when trying to compile your app after updating our plugin

Setup native projects #

You will also need to make some changes to the native projects of your React Native application.

Android #

First, add the snippet below at the bottom of your android/build.gradle file so Gradle can download the native Situm SDK dependency:

allprojects {
    repositories {
        maven {
            url "https://repo.situm.com/artifactory/libs-release-local"
        }
    }
}

Then, add the ACCESS_FINE_LOCATION permission declaration to your AndroidManifest.xml (you can omit this step if you have configured Situm SDK not to use GPS):

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

Finally, set the minSdkVersion to 21 or later on your app’s build.gradle file.

iOS #

First, you need to configure the required permissions (more info here). We outline the main steps in this tutorial, but we recommend that you make sure you comply with all the react-native permissions configurations & requirements.

First, include the following permissions in your app’s Info.plist file (modify the permission’s informative texts as you wish):

<key>NSLocationWhenInUseUsageDescription</key>
  <string>Location is required to find out where you are</string>
<key>NSLocationAlwaysUsageDescription</key>
  <string>Location is required to find out where you are</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>Location is required to find out where you are</string>

You will also need to install the Permission Handlers by adding this to your package.json:

{
  ...
  "reactNativePermissionsIOS": [
    "LocationAccuracy",
    "LocationAlways",
    "LocationWhenInUse"
  ],
  ...
}

Then, execute these lines

$ npx react-native setup-ios-permissions
$ cd ios
$ pod install

Optional steps #

If you want to enable offline support you will need to add the underlying web application’s domain inside the entry WKAppBoundDomains, also on Info.plist as follows:

<key>WKAppBoundDomains</key>
<array>
  <string>map-viewer.situm.com</string>
</array>

Sometimes, you may need to add a Header Search Path:

  $(SRCROOT)/../node_modules/react-native-situm-plugin/lib/ios

Under some React Native versions, you might also need to remove the “use_frameworks!” directive in the Podfile of your iOS project, or else configure the Podfile. This is needed because Situm SDK is a static library

Run your first app! #

The following code contains a fully functional React Native app. You may copy & paste it in your App.tsx file (you may obtain your credentials as explained here, and your building ID as explained here):

import React, {useEffect} from 'react';
import {SafeAreaView, StyleSheet} from 'react-native';

// 1. Importing dependencies
import SitumPlugin, { MapView, SitumProvider, requestPermission } from '@situm/react-native';

// 2. Define Situm SDK credentials and building identifier
const SITUM_API_KEY = 'YOUR_APIKEY';
const SITUM_BUILDING_ID = 'YOUR_BUILDING';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  mapview: {
    width: '100%',
    height: '100%',
  },
});

const Screen: React.FC = () => {
  // 3. Initialize the Situm SDK and start positioning
  useEffect(() => {

    //Initialize Situm and set credentials
    SitumPlugin.init();
    SitumPlugin.setApiKey(SITUM_API_KEY);
    // Set positioning configuration
    SitumPlugin.setConfiguration({useRemoteConfig: true});
    // Request necessary permissions to start positioning
    requestPermission()
      .then(() => {
        SitumPlugin.requestLocationUpdates();
      })
      .catch(e => {
        console.log(`Permissions rejected: ${e}`);
      });

    // Stop positioning when unmounting component
    return () => SitumPlugin.removeLocationUpdates();
  }, []);

  // 4. Show the building cartography
  return (
    <MapView
      style={{...styles.mapview}}
      configuration={{
        buildingIdentifier: SITUM_BUILDING_ID,
        situmApiKey: SITUM_API_KEY,
      }}
      onPoiSelected={poi => {
        console.log('Situm > wayfinding > Poi selected: ${poi.name}');
      }}
      onLoad={(event: any) => {
        console.log('Map is ready now' + JSON.stringify(event));
      }}
    />
  );
};

const App = () => (
  <SafeAreaView style={{...styles.container}}>
    <SitumProvider>
      <Screen />
    </SitumProvider>
  </SafeAreaView>
);

export default App;

You may run this app by using:

$ yarn start

Note! In XCode: go to root/ios folder and open SitumRNGettingStarted.xcworkspace or run the command xed ios from the root directory.

You should see something like this:

Code explanation: step-by-step #

1. Importing dependencies #

The 1st thing the example does is importing the @situm/react-native package.

2. Setting credentials and building identifier #

Right after the import, we set:

  • User credentials: APIKEY.
  • Building identifier: identifier of the building whose cartography will be shown. It should be the same as the one where you’ll perform positioning.

You may obtain your credentials as explained here, and your building ID as explained here.

3. Initialize the SDK and start positioning #

You may initialize and start positioning by using the SDK API provided by our @situm/react-native plugin detailed in the example above. To do so, you may execute the following steps:

4. Show the cartography using the MapView #

Then, the example shows the cartography of the selected building. You may see that the wayfinding library exposes two main classes to this extent:

  • MapView. The React Native component that you can add to your view hierarchy.
  • SitumProvider. This is a wrapper for your aplication that the Situm plugin uses to handle internal state. You must wrap the screen that uses Situm with this Provider or you can wrap your entire application with it as well.

More examples! Please take a look at our Example app, which contains different examples on how to perform several other actions using Situm.

Suscríbete a nuestro boletín

INFORMACIÓN BÁSICA SOBRE PROTECCIÓN DE DATOS

Responsable del tratamiento: SITUM TECHNOLOGIES, S.L.
Contacto: Responsable del tratamiento: situm@situm.es
Responsable de protección: dpo@situm.es
Finalidad y base legal: Gestionar el envío de newsletter de SITUM sólo con consentimiento.
Legitimación: Consentimiento expreso del interesado.
Destinatarios: Los datos no serán cedidos a terceros salvo obligación legal.
Plazo de conservación: Mientras la parte interesada permanezca suscrita al newsletter (en cada newsletter enviado por Situm estará disponible un link para darse de baja).
Derechos: El interesado podrá revocar en cualquier momento su consentimiento, así como ejercitar los derechos de oposición, acceso, conservación, rectificación, limitación, supresión de datos y no ser objeto de una decisión basada únicamente en el tratamiento automatizado de datos, dirigiéndose por escrito a SITUM en las direcciones indicadas.
Información Adicional: Puede consultar la información adicional y detallada sobre Protección de Datos en nuestra política de privacidad.

Por favor, descarga tu copia aquí.

Muchas gracias por descargar nuestro whitepaper. No dudes en contactar con nosotros si quieres saber más sobre cómo nuestras soluciones pueden ayudar a tu negocio.


Cerrar ventana