Skip to main content

Lesson 9 of 10

Mini Project: Location + Camera + QR Scanner

Build a location-aware QR scanner: shows user's current location, lets them scan a QR code, and marks the scanned location on a map. Combines expo-location, expo-camera, and react-native-maps.

60 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Location-Aware QR Scanner

Location-Aware QR Scanner
import { useState, useCallback } from 'react';
import { View, Text, Pressable, Alert, StyleSheet } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import * as Location from 'expo-location';
import { CameraView, useCameraPermissions, BarcodeScanningResult } from 'expo-camera';
import MapView, { Marker, PROVIDER_GOOGLE } from 'react-native-maps';
// npx expo install expo-location expo-camera react-native-maps

interface ScannedLocation {
  data: string;
  coords: { latitude: number; longitude: number };
  timestamp: number;
}

type Screen = 'map' | 'scanner';

export default function LocationQRApp() {
  const [screen, setScreen] = useState<Screen>('map');
  const [userCoords, setUserCoords] = useState<{ latitude: number; longitude: number } | null>(null);
  const [scannedLocations, setScannedLocations] = useState<ScannedLocation[]>([]);
  const [cameraPermission, requestCamera] = useCameraPermissions();
  const [locationPermission, setLocationPermission] = useState(false);

  // Load location on mount
  React.useEffect(() => {
    (async () => {
      const { status } = await Location.requestForegroundPermissionsAsync();
      if (status === 'granted') {
        setLocationPermission(true);
        const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
        setUserCoords({ latitude: loc.coords.latitude, longitude: loc.coords.longitude });
      }
    })();
  }, []);

  const handleQRScan = useCallback(async ({ data }: BarcodeScanningResult) => {
    if (!locationPermission) return;

    const loc = await Location.getCurrentPositionAsync({});
    const newScan: ScannedLocation = {
      data,
      coords: { latitude: loc.coords.latitude, longitude: loc.coords.longitude },
      timestamp: Date.now(),
    };

    setScannedLocations(prev => [...prev, newScan]);
    setScreen('map');
    Alert.alert('QR Scanned', `Content: ${data}`, [{ text: 'OK' }]);
  }, [locationPermission]);

  if (screen === 'scanner') {
    if (!cameraPermission?.granted) {
      return (
        <SafeAreaView style={s.screen}>
          <Text style={s.text}>Camera permission required</Text>
          <Pressable onPress={requestCamera} style={s.btn}><Text style={s.btnText}>Grant Access</Text></Pressable>
        </SafeAreaView>
      );
    }

    return (
      <View style={{ flex: 1 }}>
        <CameraView
          style={StyleSheet.absoluteFillObject}
          barcodeScannerSettings={{ barcodeTypes: ['qr'] }}
          onBarcodeScanned={handleQRScan}
        />
        <View style={s.qrUI}>
          <View style={s.qrFrame} />
          <Text style={s.qrHint}>Point at a QR code</Text>
          <Pressable onPress={() => setScreen('map')} style={s.cancelBtn}>
            <Text style={s.cancelText}>βœ• Cancel</Text>
          </Pressable>
        </View>
      </View>
    );
  }

  return (
    <View style={{ flex: 1 }}>
      {userCoords ? (
        <MapView
          provider={PROVIDER_GOOGLE}
          style={StyleSheet.absoluteFillObject}
          initialRegion={{ ...userCoords, latitudeDelta: 0.01, longitudeDelta: 0.01 }}
          showsUserLocation
          showsMyLocationButton
        >
          {scannedLocations.map((scan, i) => (
            <Marker
              key={i}
              coordinate={scan.coords}
              title="QR Scanned Here"
              description={scan.data.substring(0, 50)}
              pinColor="#229c6b"
            />
          ))}
        </MapView>
      ) : (
        <View style={s.screen}><Text style={s.text}>Getting your location...</Text></View>
      )}

      {/* FAB */}
      <SafeAreaView style={s.fab} edges={['bottom']} pointerEvents="box-none">
        <Pressable onPress={() => setScreen('scanner')} style={s.fabBtn} accessibilityRole="button" accessibilityLabel="Open QR scanner">
          <Text style={s.fabIcon}>πŸ”²</Text>
          <Text style={s.fabText}>Scan QR</Text>
        </Pressable>
      </SafeAreaView>
    </View>
  );
}

const s = StyleSheet.create({
  screen: { flex: 1, backgroundColor: '#0f172a', alignItems: 'center', justifyContent: 'center' },
  text: { color: '#f1f5f9', fontSize: 16, marginBottom: 16, textAlign: 'center' },
  btn: { backgroundColor: '#229c6b', padding: 14, borderRadius: 10 },
  btnText: { color: 'white', fontWeight: '700' },
  qrUI: { ...StyleSheet.absoluteFillObject, alignItems: 'center', justifyContent: 'center' },
  qrFrame: { width: 230, height: 230, borderWidth: 2, borderColor: '#229c6b', borderRadius: 14 },
  qrHint: { color: 'white', marginTop: 20, fontSize: 15, backgroundColor: '#00000099', padding: 8, borderRadius: 8 },
  cancelBtn: { position: 'absolute', top: 56, right: 20, backgroundColor: '#00000066', padding: 10, borderRadius: 20 },
  cancelText: { color: 'white', fontWeight: '700' },
  fab: { position: 'absolute', bottom: 0, left: 0, right: 0, alignItems: 'center', pointerEvents: 'box-none' },
  fabBtn: { flexDirection: 'row', gap: 8, alignItems: 'center', backgroundColor: '#229c6b', paddingHorizontal: 28, paddingVertical: 16, borderRadius: 30, marginBottom: 24, shadowColor: '#229c6b', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.4, shadowRadius: 8, elevation: 8 },
  fabIcon: { fontSize: 20 },
  fabText: { color: 'white', fontWeight: '700', fontSize: 16 },
});

Tip

Tip

Practice Mini Project Location Camera QR Scanner in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Coordinated camera viewfinder, GPS geotagging, and haptic feedback

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Location Camera QR Scanner from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Location Camera QR Scanner is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/10 done