Elective Mobile Application Development

Mobile Application DevelopmentUnit 814 min read

Location & Sensing: GPS, Sensors, APIs, and Real-World Apps

Unit 8 of Mobile Application Development covers how mobile apps detect real-world location (GPS, Wi-Fi, cell towers) and use sensors (accelerometer, gyroscope, magnetometer) to interact with the physical world. You’ll learn APIs like Google Maps, FusedLocationProvider, and sensor fusion techniques, plus how to handle e

TAKEAWAYS:

  • Location detection relies on GPS, Wi-Fi, cell towers, and sensors, each with trade-offs in accuracy, battery use, and availability.
  • Sensor fusion combines data from multiple sensors (e.g., accelerometer + gyroscope) to improve accuracy in apps like step counters or augmented reality.
  • Google Maps APIs and FusedLocationProvider simplify location-based services but require proper error handling and permissions.
  • Battery optimization is critical: continuous GPS drains power, while sensor batching reduces overhead.
  • Real-world apps use these techniques for navigation (Pathao), fitness (Google Fit), and emergency services (Ncell’s SOS).
  • Legal and ethical considerations include privacy (e.g., tracking without consent) and accuracy limits (e.g., indoor GPS challenges).

1. Location Detection Techniques

Mobile devices use multiple methods to determine location, each with pros and cons. Below is a comparison table and visual breakdown.

1.1 GPS (Global Positioning System)

How it works:

  • Uses satellites to triangulate position (minimum 3 satellites needed for 2D, 4 for 3D).
  • Accuracy: 5–10 meters (better in open areas, worse in urban canyons or indoors).
  • Power-hungry: Continuous GPS use drains battery quickly.

Visual: GPS Triangulation

SignalSignalSignalTriangulatesSatellite 1Satellite 2Satellite 3PhoneYour Location (X,Y)
GPS triangulation requires signals from at least 3 satellites (4 for altitude).

Worked Example: Pathao’s Rider Location

  • Pathao uses GPS + Wi-Fi/cell towers to track riders in real-time.
  • Problem: GPS alone fails in Kathmandu’s narrow streets. Solution: Fallback to network-based location when GPS signal is weak.
  • Code Snippet (Android):
    FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
    LocationRequest request = new LocationRequest()
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        .setInterval(10000) // 10-second updates
        .setFastestInterval(5000);
    fusedLocationClient.requestLocationUpdates(request, locationCallback, null);
    
  • Trace Table:
    Step GPS Signal Wi-Fi Available Fallback Used Location Source
    1 Weak Yes No Wi-Fi triangulation
    2 Strong No No GPS
    3 Lost No Yes Cell tower proximity

1.2 Network-Based Location (Wi-Fi, Cell Towers)

How it works:

  • Wi-Fi: Compares nearby Wi-Fi networks to a database (e.g., Google’s Wi-Fi positioning service).
  • Cell Towers: Uses signal strength from nearby towers to estimate location.
  • Accuracy: 10–100 meters (worse than GPS but works indoors).
  • Battery-efficient: No active GPS needed.
Signal Strength: HighSignal Strength: MediumSignal Strength: LowDataDataDataPhoneCell Tower ACell Tower BCell Tower CLocation Database
Cell tower triangulation: Stronger signals indicate closer proximity.

Visual: Wi-Fi Triangulation

ScansScansScansSignal StrengthSignal StrengthSignal StrengthTriangulatesPhoneWi-Fi Router 1Wi-Fi Router 2Wi-Fi Router 3DatabaseApprox. Location
Wi-Fi triangulation uses signal strength from multiple routers for indoor location estimation.

Real-World Example: Ncell’s "Find My Device"

  • Ncell uses cell tower + Wi-Fi to locate lost phones when GPS is off.
  • Why? GPS is disabled by default to save battery, but network-based location still works.

1.3 Sensor-Based Location (Accelerometer, Gyroscope)

How it works:

  • Pedometer apps (e.g., Google Fit) use the accelerometer to count steps.
  • Dead reckoning: Combines accelerometer + gyroscope to estimate movement (used in AR apps).
  • Accuracy: Low (drift over time) but useful for relative motion.

Visual: Step Detection with Accelerometer

123456789100.20.40.60.81xyAccelerometer Signal (Step Pattern)Step Peak 1Step Peak 2Step Peak 3
Accelerometer detects step patterns by analyzing motion peaks (simplified).

Worked Example: Google Fit Step Counter

  • Algorithm:
    1. Accelerometer data is filtered to remove noise.
    2. Peaks in the Z-axis (vertical movement) are detected as steps.
    3. Stride length is estimated (default: 0.762 meters/step).
  • Code Snippet (Pseudocode):
    def count_steps(accelerometer_data):
        steps = 0
        for sample in accelerometer_data:
            if sample.z > THRESHOLD:  # Peak detected
                steps += 1
        return steps * STRIDE_LENGTH
    
  • Trace Table:
    Sample Z-Axis Value Peak Detected? Step Count
    1 0.5 No 0
    2 12.3 Yes 1
    3 -0.2 No 1
    4 11.8 Yes 2

2. Sensor Fusion for Accuracy

Single sensors are error-prone. Sensor fusion combines multiple sensors for better results.

2.1 Common Sensors in Mobile Devices

Sensor Typical Use Case Accuracy
Accelerometer Step counting, tilt detection ±0.1g
Gyroscope Rotation tracking (e.g., AR apps) ±1°/second
Magnetometer Compass direction ±2°
Barometer Altitude changes ±1 meter
GPS Absolute location 5–10 meters

Visual: Sensor Fusion in a Smartphone

Real-World Example: Pokémon GO’s AR Navigation

  • Uses gyroscope + accelerometer + magnetometer to keep the screen aligned with the real world.
  • Problem: Magnetometer errors in metal-rich areas (e.g., near power lines).
  • Solution: Kalman Filter (a math algorithm) fuses sensor data to smooth out errors.

3. Location APIs and Services

Mobile apps rarely implement location detection from scratch. Instead, they use APIs provided by Google, Apple, or third parties.

3.1 Google Maps Platform (Android/iOS)

  • Services:
    • Places API: Search for nearby restaurants, ATMs (used by Daraz for delivery pin drops).
    • Directions API: Real-time navigation (like Pathao’s route planning).
    • Geocoding API: Convert addresses to coordinates (e.g., "Kathmandu 44600" → latitude/longitude).
  • Permissions Required:
    <!-- AndroidManifest.xml -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    

Visual: Google Maps API Workflow

sequenceDiagram
    App->>Google Maps API: Request Location
    Google Maps API->>GPS/Wi-Fi: Get Data
    Google Maps API-->>App: Return Coordinates
    App->>UI: Update Map View

Worked Example: Daraz Delivery Pin Drop

  1. Customer selects a delivery address (e.g., "Thapathali, Kathmandu").
  2. Geocoding API converts this to latitude: 27.7073, longitude: 85.3162.
  3. Directions API calculates the fastest route from the warehouse.
  4. FusedLocationProvider tracks the delivery person’s live location.

3.2 Apple’s Core Location (iOS)

  • Similar to Android’s FusedLocationProvider but optimized for iOS.
  • Supports significant location changes (battery-efficient updates when moving between cities).

Code Snippet (Swift):

import CoreLocation
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()

4. Challenges and Optimizations

4.1 Common Issues

Issue Cause Solution
High battery drain Continuous GPS updates Use setInterval() wisely
Low accuracy indoors GPS signal blocked Fallback to Wi-Fi/cell towers
Permission denied User revoked location access Request permissions gracefully
Sensor drift Gyroscope/accelerometer errors Use sensor fusion (Kalman Filter)

Visual: Battery Impact of Location Updates

015304560GPS (Continuous)60Wi-Fi/Cell Towers25Sensor-Only15Battery Usage (%)
Battery impact comparison: GPS drains the most, while sensor-only methods are efficient.

4.2 Optimizations

  • Batch updates: Reduce frequency of location requests (e.g., update every 30 seconds instead of every second).
  • Use getLastKnownLocation(): Avoids cold-start delays.
  • Hybrid approach: Combine GPS (when available) with network-based location (fallback).

5. Real-World Applications in Nepal

App/Service Location/Sensing Technique Used Example Use Case
Pathao GPS + FusedLocationProvider Rider tracking, ETA calculation
Ncell SOS Cell tower triangulation Emergency location sharing
Google Maps (Nepal) GPS + Geocoding API Navigation, "Nearby ATMs" search
eSewa GPS (for delivery agents) Tracking eSewa parcel delivery
NTC Traffic App Wi-Fi/cell towers + sensor fusion Real-time traffic updates
Khalti Pay Device proximity (Bluetooth/NFC) Secure in-store payments

Worked Example: NTC Traffic Monitoring

  • Problem: Kathmandu traffic is unpredictable. NTC wants to show real-time congestion.
  • Solution:
    1. Sensor Fusion: Combine accelerometer (vehicle speed) + GPS (location).
    2. Edge Computing: Process data on the phone to reduce cloud load.
    3. Map Overlay: Display congestion zones on Google Maps.
  • Visual: Traffic Data Collection
SpeedJerk DetectionSent to CloudCar's GPSAccelerometerTraffic Jam LikelyNTC Traffic Map
Sensor fusion for traffic data: GPS + accelerometer detects congestion patterns.

  • Privacy: Apps must disclose how location data is used (e.g., "We collect location for navigation only").
  • Consent: Always request ACCESS_FINE_LOCATION permission at runtime (not just in manifest).
  • Accuracy Warnings: Inform users if location is approximate (e.g., "Your location is estimated within 50 meters").

Visual: Permission Flow (Android)

flowchart TD
    A["App Launches"] --> B["Check Location Permission"]
    B -->|"Granted"| C["Enable Location Updates"]
    B -->|"Denied"| D["Show Why Needed"]
    D -->|"User Grants"| C

Exam Tip

This unit is heavily practical in exams. Expect:

  1. Short-answer questions on GPS vs. Wi-Fi accuracy, sensor fusion, or API permissions.

    • Example: "Why does Pathao use FusedLocationProvider instead of raw GPS?" Answer: "To combine GPS, Wi-Fi, and cell tower data for better accuracy and battery efficiency, especially in urban areas like Kathmandu where GPS signals are weak."
  2. Code snippets where you must:

    • Write a LocationRequest for high-accuracy updates.
    • Explain how to handle onLocationResult callbacks.
    • Trace a step-counting algorithm with sample accelerometer data.
  3. Scenario-based questions:

    • Example: "Design a location system for a delivery app in Pokhara where GPS is often blocked by hills. What fallback methods would you use?" Answer:
      • Primary: GPS (when available).
      • Fallback 1: Wi-Fi triangulation (if connected to known networks).
      • Fallback 2: Cell tower proximity (if Wi-Fi is off).
      • Optimization: Batch updates every 15 seconds to save battery.
  4. Diagram-based questions:

    • Draw a sensor fusion workflow (accelerometer + gyroscope → stable orientation).
    • Sketch a GPS triangulation with 3 satellites.
    • Show a mermaid sequence diagram for how Google Maps API processes a location request.

Common Pitfalls to Avoid:

  • Forgetting to request runtime permissions (exams may ask: "Why does this app crash on Android 6+").
  • Ignoring battery optimizations (e.g., using PRIORITY_HIGH_ACCURACY when PRIORITY_BALANCED_POWER_ACCURACY would suffice).
  • Overlooking edge cases (e.g., "What if GPS is unavailable and Wi-Fi is off?").

Pro Tip: Memorize the accuracy and power trade-offs of each method (GPS > Wi-Fi > Cell Towers in accuracy, but GPS drains battery fastest). Examiners love questions like: "Which method would you choose for an app that tracks school bus locations in Bhaktapur, and why?"

Based on the TU BSc CSIT syllabus for Mobile Application Development, unit 8.

Discussion

Loading…