Building an on-premise mode
In this tutorial, we show you how to use geofences in Radar to show an on-premise mode when a user is in a geofence.
#
Steps#
Step 1: Sign up for RadarIf you haven't already, sign up for Radar to get your API key. You can create up to 1,000 geofences and make up to 100,000 API requests per month for free.
Get API keys#
Step 2: Create geofencesThere are several ways to create geofences:
The tag
is a group for the geofence. For example, you could set tag = venue
for gaming, or tag = restaurant
for restaurants. In this tutorial, we're going to use tag = store
.
#
Step 3: Initialize the SDKInitialize the SDK with your publishable API key.
- Swift
- Kotlin
- Web
- React Native
- Flutter
import UIKitimport RadarSDK
@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Radar.initialize(publishableKey: "prj_test_pk_...") Radar.setUserId("foo")
return true }
}
import io.radar.sdk.Radar
class MyApplication : Application() {
override fun onCreate() { super.onCreate()
Radar.initialize(this, "prj_test_pk...") Radar.setUserId("foo") }
}
<html> <head> <title>Hello, world!</title> <script src="https://js.radar.com/v4/radar.min.js"></script> </head> <body> <div id="content"> </div>
<script type="text/javascript"> Radar.initialize("prj_test_pk_..."); Radar.setUserId("foo") </script> </body></html>
import React, { useState, useEffect } from "react";import Radar from "react-native-radar";
export default function App() { useEffect(() => { Radar.initialize("prj_live_pk_..."); Radar.setUserId("foo") }, []);
return ( <div id="content"> </div> );}
import 'package:flutter/material.dart';import 'package:flutter_radar/flutter_radar.dart';
void main() { runApp(MyApp());}
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( home: RadarTrackingScreen(), ); }}
class RadarTrackingScreen extends StatefulWidget { const RadarTrackingScreen({super.key});
@override _RadarTrackingScreenState createState() => _RadarTrackingScreenState();}
class _RadarTrackingScreenState extends State<RadarTrackingScreen> { @override void initState() { super.initState(); _initializeRadar(); }
void _initializeRadar() { Radar.initialize("prj_test_pk_..."); // Replace with your actual Radar publishable key Radar.setUserId('flutter-test-user'); Radar.setDescription('Flutter'); Radar.setMetadata({'foo': 'bar', 'bax': true, 'qux': 1}); Radar.setLogLevel('debug'); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Radar Tracking')), body: const Center( child: Text('Initialized Radar SDK'), ), ); }}
#
Step 4: Request foreground permissions- Swift
- Kotlin
- Web
- React Native
- Flutter
import UIKitimport RadarSDKimport CoreLocation
@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Radar.initialize(publishableKey: "prj_test_pk_...") Radar.setUserId("foo")
self.locationManager.delegate = self self.requestLocationPermissions()
return true }
func requestLocationPermissions() { let status = self.locationManager.authorizationStatus
if status == .notDetermined { self.locationManager.requestWhenInUseAuthorization() } }
}
import android.Manifestimport android.app.AlertDialogimport android.content.pm.PackageManagerimport android.os.Build
import androidx.core.app.ActivityCompat
import io.radar.sdk.Radar
class MainActivity : AppCompatActivity() { private val foregroundLocationPermissionsRequestCode = 1
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
Radar.initialize(this, "prj_test_pk_...") Radar.setUserId("foo")
requestLocationPermissions() }
private fun requestLocationPermissions() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), foregroundLocationPermissionsRequestCode) } }
}
When Radar.trackOnce()
is called, the browser will automatically prompt for foreground permissions.
<html> <head> <title>Hello, world!</title> <script src="https://js.radar.com/v4/radar.min.js"></script> </head> <body> <div id="content"> </div>
<script type="text/javascript"> Radar.initialize("prj_test_pk_..."); Radar.setUserId("foo");
Radar.trackOnce(); </script> </body></html>
import React, { useState, useEffect } from "react";import Radar from "react-native-radar";
export default function App() { useEffect(() => { Radar.initialize("prj_live_pk_..."); Radar.setUserId("foo")
Radar.requestPermissions(false).then((status) => { // status will be "GRANTED_FOREGROUND" if permissions were granted }); }, []);
return ( <div id="content"> </div> );}
Learn about platform-specific permissions in the iOS SDK documentation and Android SDK documentation.
import 'package:flutter/material.dart';import 'package:flutter_radar/flutter_radar.dart';
void main() { runApp(MyApp());}
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( home: RadarTrackingScreen(), ); }}
class RadarTrackingScreen extends StatefulWidget { const RadarTrackingScreen({super.key});
@override _RadarTrackingScreenState createState() => _RadarTrackingScreenState();}
class _RadarTrackingScreenState extends State<RadarTrackingScreen> { String _displayText = 'Initialized Radar SDK';
@override void initState() { super.initState(); _initializeRadar(); _requestPermissionsAndTrack(); }
void _initializeRadar() { Radar.initialize("prj_test_pk_...."); // Replace with your actual Radar publishable key Radar.setUserId('flutter-test-user'); Radar.setDescription('Flutter'); Radar.setMetadata({'foo': 'bar', 'bax': true, 'qux': 1}); Radar.setLogLevel('debug'); }
Future<void> _requestPermissionsAndTrack() async { // Initial permission status check var permissionStatus = await Radar.getPermissionsStatus();
// Check if permissions are not determined if (permissionStatus == 'NOT_DETERMINED') { print('Requesting foreground permissions...'); await Radar.requestPermissions(false); // Request foreground permission }
// Status will be "GRANTED_FOREGROUND" if permissions were granted if (permissionStatus == 'GRANTED_FOREGROUND') { // Activate on-premise experience here } else { // Handle denied permissions print('Location permissions not granted'); setState(() { _displayText = 'Permissions denied, tracking is disabled.'; }); }}
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Radar Tracking')), body: const Center( child: Text(_displayText), ), ); }}
#
Step 5: Change the UI when the user is in a geofenceCall Radar.trackOnce()
to track the user's location in the foreground. In the callback, check user.geofences
to determine if the user is in a store, then change the UI to show the on-premise experience.
- Swift
- Kotlin
- Web
- React Native
- Flutter
import UIKitimport RadarSDKimport CoreLocation
@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { Radar.initialize(publishableKey: "prj_test_pk_...") Radar.setUserId("foo")
self.locationManager.delegate = self self.requestLocationPermissions()
Radar.trackOnce { (status, location, events, user) in let isInStore = user?.geofences?.contains { $0.tag == "store" } if isInStore { // show on-premise mode } }
return true }
func requestLocationPermissions() { let status = self.locationManager.authorizationStatus
if status == .notDetermined { self.locationManager.requestWhenInUseAuthorization() } }
}
import android.Manifestimport android.app.AlertDialogimport android.content.pm.PackageManagerimport android.os.Build
import androidx.core.app.ActivityCompat
import io.radar.sdk.Radar
class MainActivity : AppCompatActivity() { private val foregroundLocationPermissionsRequestCode = 1
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
Radar.initialize(this, "prj_test_pk_...") Radar.setUserId("foo")
requestLocationPermissions() }
override fun onStart() { super.onStart()
Radar.trackOnce { status, location, events, user -> val isInStore = user?.geofences?.any { geofence.tag == "store" } if (isInStore) { // show on-premise mode } } }
private fun requestLocationPermissions() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), foregroundLocationPermissionsRequestCode) } }
}
<html> <head> <title>Hello, world!</title> <script src="https://js.radar.com/v4/radar.min.js"></script> </head> <body> <div id="content"> </div>
<script type="text/javascript"> Radar.initialize("prj_test_pk_..."); Radar.setUserId("foo");
Radar.trackOnce().then((result) => { const user = result.user; for (const geofence of user.geofences) { if (geofence.tag === 'store') { // show on-premise mode } } }).catch((err) => { // handle error }); </script> </body></html>
import React, { useState, useEffect } from "react";import Radar from "react-native-radar";
export default function App() { const [isInStore, setIsInStore] = useState(false);
useEffect(() => { Radar.initialize("prj_live_pk_..."); Radar.setUserId("foo");
Radar.requestPermissions(false).then((status) => { // status will be "GRANTED_FOREGROUND" if permissions were granted
Radar.trackOnce().then((result) => { const { user } = result; for (const geofence of user.geofences) { if (geofence.tag === 'store') { setIsInStore(true); } } }).catch((err) => { // handle error }); }); }, []);
return ( <div id="content"> { isInStore ? ( {/* Show on-premise mode */} ) : ( {/* Show default UI */} )} </div> );}
import 'package:flutter/material.dart';import 'package:flutter_radar/flutter_radar.dart';
void main() { runApp(MyApp());}
class MyApp extends StatelessWidget { const MyApp({super.key});
@override Widget build(BuildContext context) { return MaterialApp( home: RadarTrackingScreen(), ); }}
class RadarTrackingScreen extends StatefulWidget { const RadarTrackingScreen({super.key});
@override _RadarTrackingScreenState createState() => _RadarTrackingScreenState();}
class _RadarTrackingScreenState extends State<RadarTrackingScreen> { String _displayText = 'Initialized Radar SDK';
@override void initState() { super.initState(); _initializeRadar(); _requestPermissionsAndTrack(); }
void _initializeRadar() { Radar.initialize("prj_test_pk_..."); // Replace with your actual Radar publishable key Radar.setUserId('flutter-test-user'); Radar.setDescription('Flutter'); Radar.setMetadata({'foo': 'bar', 'bax': true, 'qux': 1}); Radar.setLogLevel('debug'); }
Future<void> _requestPermissionsAndTrack() async { // Initial permission status check var permissionStatus = await Radar.getPermissionsStatus();
// Check if permissions are not determined if (permissionStatus == 'NOT_DETERMINED') { print('Requesting foreground permissions...'); permissionStatus = await Radar.requestPermissions(false); // Request foreground permission }
if (permissionStatus == 'GRANTED_FOREGROUND') { var res = await Radar.trackOnce();
// Check if the user is in a geofence to activate on-premise mode var geofences = res?['user']?['geofences']; if (geofences!= null && geofences.isNotEmpty) { // If user is in a geofence, activate on-premise mode setState(() { _displayText = 'In geofence: ${geofences[0]['description']}'; }); } else { // User is not in a geofence print('User is not in any geofence'); } } else { // Handle denied permissions print('Location permissions not granted'); setState(() { _displayText = 'Permissions denied, tracking is disabled.'; }); } }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Radar Tracking')), body: Center( child: Text(_displayText), // Display on-premise mode ), ); }}
#
SupportHave questions or feedback on this documentation? Let us know! Contact us at radar.com/support.