Elective Mobile Application Development

Mobile Application DevelopmentUnit 816 min read

Location & Sensing: GPS, Sensors, APIs & Context-Aware Apps

Unit 8 of Mobile Application Development covers how mobile apps detect real-world location (GPS, Wi-Fi, cell towers), use onboard sensors (accelerometer, gyroscope, magnetometer), and process sensor data for context-aware services like navigation, fitness tracking, and augmented reality.

TAKEAWAYS:

  • Mobile devices combine GPS, Wi-Fi trilateration, and cell tower triangulation to estimate location, with trade-offs in accuracy and battery use.
  • Sensors (accelerometer, gyroscope, magnetometer, barometer) detect motion, orientation, and environmental changes, enabling features like step counting, compass apps, and altitude tracking.
  • Location APIs (Google Maps, Mapbox, Ncell’s GeoFencing) provide geocoding, routing, and real-time traffic data, while sensor APIs (Android SensorManager, iOS CoreMotion) access raw sensor data.
  • Context-awareness uses sensor fusion (combining multiple sensors) to infer user activities (e.g., walking vs. driving) or environmental conditions (e.g., altitude for hiking apps).
  • Privacy and battery optimization are critical: apps must request location permissions, use efficient sensor sampling rates, and cache data to minimize power drain.
  • Real-world apps (Pathao for dynamic routing, Daraz for geotagged ads, NTC’s traffic monitoring) rely on these techniques to deliver location-based services.

1. Location Detection Techniques

Mobile devices estimate location using three primary methods, each with trade-offs in accuracy, speed, and battery impact.

0250005000075000100000GPS5Wi-Fi Trilateration30Cell Tower Triangulation200IP Address100000Accuracy (meters)
Comparison of location detection methods (lower = more precise).
20000220001800021000Satellite 1Satellite 2Satellite 3Satellite 4Device
GPS trilateration: Device calculates position using distances to 4 satellites (values in km).

1.1 GPS (Global Positioning System)

  • Uses satellite signals to calculate latitude, longitude, and altitude.
  • Accuracy: 2–10 meters (better outdoors, worse in urban canyons or indoors).
  • Battery impact: High (GPS chip continuously listens for signals).
  • How it works:
    • The device receives signals from at least 4 satellites (for trilateration).
    • Each satellite transmits its position and timestamp.
    • The device calculates its distance from each satellite using signal travel time.
    • The intersection of these distances gives the device’s location.
graph LR
    A["Device"] -->|"Signal"| B["Satellite 1"]
    A -->|"Signal"| C["Satellite 2"]
    A -->|"Signal"| D["Satellite 3"]
    A -->|"Signal"| E["Satellite 4"]
    B -->|"Distance"| F["Distance Calculation"]
    C -->|"Distance"| F
    D -->|"Distance"| F
    E -->|"Distance"| F
    F -->|"Trilateration"| G["Location (X,Y,Z)"]

Worked Example: Pathao’s Rider Location Pathao uses GPS to track rider locations in real time. Suppose a rider’s app receives signals from 4 satellites with the following data:

  • Satellite 1: Distance = 20,000 km, Position = (X₁, Y₁, Z₁)
  • Satellite 2: Distance = 22,000 km, Position = (X₂, Y₂, Z₂)
  • Satellite 3: Distance = 18,000 km, Position = (X₃, Y₃, Z₃)
  • Satellite 4: Distance = 21,000 km, Position = (X₄, Y₄, Z₄)

The app solves the system of equations to find the rider’s coordinates. If the rider moves, the app recalculates every few seconds for smooth tracking.

Visual: GPS Signal Reception


1.2 Wi-Fi and Bluetooth Trilateration

  • Uses nearby Wi-Fi routers or Bluetooth beacons to estimate location.
  • Accuracy: 10–50 meters (better indoors where GPS fails).
  • How it works:
    • The device scans for nearby Wi-Fi networks or Bluetooth devices.
    • It measures the signal strength (RSSI) of each access point.
    • The device compares RSSI to a pre-built database of known access points (e.g., Google’s Wi-Fi positioning service).
    • Trilateration or fingerprinting determines the most likely location.

Comparison Table: Location Methods

Method Accuracy Speed Battery Impact Best Use Case
GPS 2–10 meters Slow (1s+) High Outdoor navigation
Wi-Fi Trilateration 10–50 meters Fast (<1s) Medium Indoor positioning
Cell Tower Triangulation 50–500 meters Fast (<1s) Low Emergency services
IP Address City-level Instant None Broad location (e.g., ads)

1.3 Cell Tower Triangulation

  • Uses signal strength from nearby cell towers to estimate location.
  • Accuracy: 50–500 meters (least accurate but works everywhere).
  • How it works:
    • The device measures the signal strength from 3+ cell towers.
    • The phone’s OS (or a server) calculates the device’s likely position based on tower locations and signal attenuation.

Real-World Example: NTC’s Traffic Monitoring The Nepal Telecommunications Company (NTC) uses cell tower data to estimate the location of mobile users during traffic congestion. If many users in a grid cell report slow data speeds, NTC infers heavy traffic and can alert drivers via apps like NTC Traffic Alert.


2. Mobile Sensors and Their Applications

Mobile devices include motion sensors, environmental sensors, and positioning sensors. Each serves specific app functionalities.

-2-1.5-1-0.50.511.5233.544.55yAcceleration (m/s²)Gyroscope (degrees/s)Step 1Step 2Step 3
Sensor fusion: Accelerometer (linear) + Gyroscope (angular) data during walking (Google Fit example).

2.1 Motion Sensors

Sensor Measures Key Applications Example Apps
Accelerometer Linear acceleration (X, Y, Z) Step counting, tilt detection, freefall Google Fit, Pokémon GO
Gyroscope Angular velocity (rotation) Compass calibration, 3D motion tracking VR apps, augmented reality
Magnetometer Magnetic field (for compass) Digital compass, orientation locking Hiking apps, metal detection
Barometer Atmospheric pressure (altitude) Altitude tracking, weather prediction Paragliding apps, hiking apps

Worked Example: Step Counting in Google Fit Google Fit uses the accelerometer to count steps. Here’s how:

  1. The sensor detects acceleration patterns (e.g., periodic up-down motion).
  2. The app applies a threshold filter (e.g., >3m/s² for 0.2s = 1 step).
  3. It uses sensor fusion (combining accelerometer + gyroscope) to reduce errors from device tilt.

Visual: Accelerometer Data During Walking


2.2 Environmental Sensors

Sensor Measures Key Applications Example Apps
Light Sensor Ambient light intensity Auto-brightness, camera adjustments Camera apps, accessibility features
Proximity Sensor Distance to nearest object Sleep mode, touchless UI Smartphones, fitness trackers
Humidity Sensor Relative humidity Weather apps, indoor climate control Smart home systems
Temperature Sensor Ambient temperature Health monitoring, weather alerts Smartwatches, medical apps

Real-World Example: Daraz’s "Nearby Stores" Feature Daraz uses the proximity sensor to detect when a user’s phone is near their face (e.g., during a call). If the user walks into a Daraz store, the app can trigger a geofenced promotion (e.g., "You’re near Daraz Kathmandu! 20% off today").


3. Location and Sensor APIs

Developers access location and sensor data via platform-specific APIs.

3.1 Location APIs

API/Service Provider Key Features Example Use Case
Google Maps API Google Geocoding, routing, real-time traffic Pathao, Uber, Google Maps
Mapbox Mapbox Custom maps, indoor positioning Real estate apps, museums
Ncell GeoFencing Ncell (Nepal) Location-based alerts, advertising Ncell’s "Nearby ATMs" service
Core Location (iOS) Apple High-accuracy indoor positioning Apple Maps, fitness apps
Fused Location Provider (Android) Google Combines GPS, Wi-Fi, and cell tower data Android Auto, navigation apps

Worked Example: NEPSE Stock Alerts via GeoFencing NEPSE (Nepal Stock Exchange) uses geo-fencing to send alerts to traders near the exchange building. Steps:

  1. The app registers a geo-fence around the NEPSE office (latitude: 27.7172°, longitude: 85.3240°).
  2. When a user enters the fence, the app triggers a notification: "You’re near NEPSE! Check today’s market trends."
  3. The app uses Google Maps Geofencing API to monitor entry/exit.
sequenceDiagram
    participant User
    participant App
    participant GoogleMapsAPI
    User->>App: Enters NEPSE geo-fence
    App->>GoogleMapsAPI: Check location
    GoogleMapsAPI-->>App: Location confirmed
    App->>User: Show alert

3.2 Sensor APIs

Platform/API Key Methods/Classes Example Use Case
Android (SensorManager) registerListener(), getDefaultSensor() Step counter, motion detection
iOS (CoreMotion) CMMotionManager, CMAccelerometer Fitness tracking, AR apps
Unity (Input.gyro) Input.gyro.attitude VR/AR games

Worked Example: WhatsApp’s "Last Seen" Timer Reset WhatsApp uses the accelerometer to detect when you’re typing (rapid motion) or walking (periodic motion). If the sensor detects no motion for 5 minutes, it assumes you’re idle and updates the "last seen" timestamp.


4. Sensor Fusion and Context Awareness

Sensor fusion combines data from multiple sensors to improve accuracy. Context awareness uses fused data to infer user activities.

stateDiagram-v2
    [*] --> Walking
    Walking --> Driving : (Accelerometer < 0.5m/s² + Gyroscope stable)
    Driving --> Walking : (Accelerometer > 1.5m/s² + Magnetometer change)
    Walking --> Biking : (Barometer altitude drop > 5m/min)
    Biking --> Stationary : (All sensors idle > 30s)
    Stationary --> [*]
    note right of Walking
        Context: Walking detected
        by accelerometer + gyro
    end note
Finite-state machine for activity recognition (e.g., Pathao’s rider mode detection).

4.1 Sensor Fusion Techniques

Technique Description Example
Kalman Filter Predicts sensor errors over time Google Fit’s step counting
Complementary Filter Combines accelerometer + gyroscope VR headset orientation
Dead Reckoning Estimates position based on past motion Indoor navigation (e.g., malls)

Visual: Sensor Fusion in a Smartwatch


4.2 Context-Aware Applications

Context Sensors Used App Example
Walking vs. Driving Accelerometer, GPS Google Maps (auto-detects transport)
Sleep Tracking Accelerometer, heart rate Fitbit, Apple Watch
Altitude Hiking Barometer, GPS AllTrails, Komoot
Metal Detection Magnetometer Treasure hunting apps

Worked Example: Khalti’s "Pay Nearby" Feature Khalti uses sensor fusion to improve payment success rates:

  1. Proximity sensor: Detects if the phone is near the merchant’s QR code.
  2. Accelerometer: Confirms the user is holding the phone steady (not moving).
  3. GPS: Verifies the user is within 50 meters of the merchant. Only when all conditions are met does Khalti allow payment to proceed, reducing fraud.

5. Challenges and Best Practices

5.1 Key Challenges

Challenge Impact Solution
Battery Drain GPS/sensors consume power Use low-power modes, batch updates
Privacy Concerns Location data is sensitive Request permissions, anonymize data
Indoor Accuracy GPS fails indoors Use Wi-Fi/Bluetooth beacons
Sensor Noise False readings from motion Apply filters (e.g., Kalman Filter)

5.2 Best Practices for Developers

  • Minimize GPS usage: Use passive location updates (e.g., only when the app is open).
  • Optimize sensor sampling rate: Reduce from 100Hz to 10Hz if high precision isn’t needed.
  • Cache location data: Store the last known location to avoid repeated GPS queries.
  • Handle permission denials gracefully: Provide fallback methods (e.g., IP-based location).
  • Test on real devices: Sensor behavior varies across hardware (e.g., Samsung vs. iPhone).

In the Real World

  1. Pathao’s Dynamic Routing

    • Idea Used: GPS + Real-time Traffic API
    • How: Pathao’s app fetches live traffic data from Google Maps API and combines it with the rider’s GPS location to reroute dynamically. If a road is congested, the app suggests an alternative path, reducing trip time by up to 30%.
  2. NTC’s Traffic Congestion Alerts

    • Idea Used: Cell Tower Triangulation + Data Analytics
    • How: NTC analyzes signal strength data from thousands of phones to detect slowdowns. If 50% of users in a grid cell report <1 Mbps speeds, NTC flags it as "heavy traffic" and pushes alerts via SMS or apps like NTC Traffic.
  3. Daraz’s "Nearby Deals" Push Notifications

    • Idea Used: GeoFencing + Proximity Sensor
    • How: When a user walks into a Daraz store, the app uses geo-fencing to trigger a notification: "You’re near Daraz Kathmandu! Get 15% off today." The proximity sensor ensures the phone isn’t in a pocket (e.g., during a call), confirming the user is actively shopping.

Exam Tip

This unit is heavily practical in exams. Expect:

  • Short-answer questions on sensor types (e.g., "Name two sensors used in step counting").
  • Scenario-based questions (e.g., "How would you implement a hiking app that tracks altitude?").
  • Code snippets (e.g., Android’s SensorManager or iOS’s CLLocationManager).
  • Comparison tables (e.g., "Differentiate GPS and Wi-Fi trilateration").

Key Focus Areas for Exams:

  1. Location methods: Know the accuracy, speed, and use cases of GPS, Wi-Fi, and cell tower triangulation.
  2. Sensor applications: Memorize which sensor does what (e.g., accelerometer = steps, magnetometer = compass).
  3. APIs: Be familiar with Google Maps API, Android’s SensorManager, and iOS’s CoreLocation.
  4. Sensor fusion: Understand how combining sensors improves accuracy (e.g., Kalman Filter for step counting).
  5. Real-world apps: Link concepts to apps like Pathao, Khalti, or NTC traffic alerts.

Common Pitfalls to Avoid:

  • Confusing GPS (satellite-based) with Wi-Fi trilateration (router-based).
  • Forgetting that indoor positioning requires Wi-Fi/Bluetooth, not GPS.
  • Ignoring battery optimization in answers (always mention low-power modes).
  • Overlooking privacy considerations (e.g., permission requests are mandatory).

Visual Summary: Location and Sensing Workflow


In the real world

  • Pathao (Nepal) uses GPS + sensor fusion to dynamically reroute riders in Kathmandu, adjusting for traffic (cell tower data) and pedestrian movement (accelerometer).
  • Ncell’s GeoFencing triggers alerts when a user enters/exits predefined zones (e.g., school boundaries), combining Wi-Fi trilateration (indoors) and cell tower triangulation (outdoors).
  • Daraz’s ‘Near You’ ads rely on IP-based location (city-level) for broad targeting and GPS (meter-level) for hyperlocal promotions near user’s current position.

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

Discussion

Loading…