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
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.
Visual: Wi-Fi Triangulation
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
Worked Example: Google Fit Step Counter
- Algorithm:
- Accelerometer data is filtered to remove noise.
- Peaks in the Z-axis (vertical movement) are detected as steps.
- 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 ViewWorked Example: Daraz Delivery Pin Drop
- Customer selects a delivery address (e.g., "Thapathali, Kathmandu").
- Geocoding API converts this to latitude: 27.7073, longitude: 85.3162.
- Directions API calculates the fastest route from the warehouse.
- FusedLocationProvider tracks the delivery person’s live location.
3.2 Apple’s Core Location (iOS)
- Similar to Android’s
FusedLocationProviderbut 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
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:
- Sensor Fusion: Combine accelerometer (vehicle speed) + GPS (location).
- Edge Computing: Process data on the phone to reduce cloud load.
- Map Overlay: Display congestion zones on Google Maps.
- Visual: Traffic Data Collection
6. Ethical and Legal Considerations
- Privacy: Apps must disclose how location data is used (e.g., "We collect location for navigation only").
- Consent: Always request
ACCESS_FINE_LOCATIONpermission 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"| CExam Tip
This unit is heavily practical in exams. Expect:
Short-answer questions on GPS vs. Wi-Fi accuracy, sensor fusion, or API permissions.
- Example: "Why does Pathao use
FusedLocationProviderinstead 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."
- Example: "Why does Pathao use
Code snippets where you must:
- Write a
LocationRequestfor high-accuracy updates. - Explain how to handle
onLocationResultcallbacks. - Trace a step-counting algorithm with sample accelerometer data.
- Write a
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.
- 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:
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_ACCURACYwhenPRIORITY_BALANCED_POWER_ACCURACYwould 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…