IT272 Mobile Application Development

Mobile Application DevelopmentUnit 815 min read

Location Services, Maps, Geocoding, and Navigation in Mobile Apps

Unit 8 of Mobile Application Development covers how mobile apps access real-world location data, integrate maps (Google Maps, Mapbox), perform geocoding (address ↔ coordinates), and implement navigation (routes, directions). It explains APIs, permissions, accuracy trade-offs, and real-world use cases like ride-hailing

TAKEAWAYS:

  • Mobile apps use GPS, Wi-Fi, cell towers, and sensors to determine location, each with trade-offs in accuracy and battery use.
  • Geocoding converts between addresses and coordinates (e.g., "Kathmandu" ↔ 27.7172° N, 85.3240° E), while reverse geocoding does the opposite.
  • Google Maps SDK and Mapbox provide maps, markers, and route calculations via APIs, but require API keys and proper permissions.
  • Navigation relies on Directions API (Google) or OpenStreetMap for turn-by-turn instructions, optimized for walking, driving, or transit.
  • Location permissions (ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION) must be declared and requested at runtime, with fallback strategies for denied access.
  • Offline maps and caching improve performance in low-connectivity areas (e.g., rural Nepal), but increase app size.

1. Location Acquisition in Mobile Apps

Mobile devices determine location using a combination of hardware and software techniques. The accuracy and battery impact vary by method:

1.1 Location Sources and Their Trade-offs

classDiagram
    class LocationSource {
        <<abstract>>
        +getAccuracy() Meter
        +getBatteryImpact() Low/Medium/High
        +getAvailability() Indoor/Outdoor
    }
    class GPS {
        +usesSatellites()
        +accuracy: ~5-10m (outdoor)
        +battery: High
    }
    class Network {
        +usesCellTowers/WiFi
        +accuracy: ~50-1000m
        +battery: Low
    }
    class Sensor {
        +usesAccelerometer/Gyroscope
        +accuracy: ~1-5m (short distances)
        +battery: Medium
    }
    LocationSource <|-- GPS
    LocationSource <|-- Network
    LocationSource <|-- Sensor
0125250375500GPS10Network500Sensor Fusion3Accuracy (meters)
Typical accuracy ranges for location sources (outdoor conditions)
Source Accuracy Battery Impact Availability Use Case
GPS 5–10 m (outdoor) High Outdoor, clear sky Hiking apps, navigation (Pathao)
Network 50–1000 m Low Indoor/outdoor Location-based ads (eSewa)
Wi-Fi 10–100 m Medium Urban areas Indoor positioning (malls)
Cell Towers 100–1000 m Low Rural/urban Fallback for GPS (Ncell apps)
Sensor Fusion 1–5 m (short-term) Medium Indoor/outdoor Pedestrian navigation (Google Maps)

1.2 How Android Fuses Location Data

Android’s Fused Location Provider combines multiple sources to improve accuracy and battery life:

  1. GPS provides high accuracy but drains battery.
  2. Network (Wi-Fi/cell towers) fills gaps when GPS is weak.
  3. Sensor fusion (accelerometer/gyroscope) corrects short-term movements.

Example: In a Pathao driver app, the app starts with network-based location (low battery) and switches to GPS when the driver moves, then falls back to sensor fusion in traffic jams.


2. Geocoding: Address ↔ Coordinates

Geocoding converts between human-readable addresses and geographic coordinates (latitude/longitude).

2.1 Forward vs. Reverse Geocoding

flowchart TD
    A["Forward Geocoding\nAddress → Coordinates"] -->|"e.g., 'Kathmandu'"| B["API Call\nGoogle Maps/Mapbox"]
    B --> C["{lat: 27.7172, lng: 85.3240}"]
    D["Reverse Geocoding\nCoordinates → Address"] -->|"e.g., {27.7172, 85.3240}"| E["API Call"]
    E --> F["'Kathmandu Metropolitan City, Nepal'"]

Example: eSewa Location Search When you type "Thamel, Kathmandu" in eSewa’s service locator:

  1. The app sends "Thamel, Kathmandu" to Google Maps Geocoding API.
  2. The API returns {lat: 27.7102, lng: 85.3239}.
  3. The app plots this on a map and shows nearby eSewa centers.

2.2 How Geocoding Works (Step-by-Step)

sequenceDiagram
    participant User
    participant App
    participant GoogleMapsAPI
    User->>App: Types "Kathmandu University"
    App->>GoogleMapsAPI: POST /geocode?address=KU
    GoogleMapsAPI-->>App: {"lat": 27.7070, "lng": 85.3241, "place_name": "KU, Dhulikhel"}
    App->>App: Plot marker at (27.7070, 85.3241)
    App->>App: Show address: 'Kathmandu University'
    Note right of App: Accuracy: ±10m (varies by location)
    Note right of GoogleMapsAPI: API Response Time: ~200ms

API Request Example (Google Maps):

GET https://maps.googleapis.com/maps/api/geocode/json?
    address=Kathmandu+University&
    key=YOUR_API_KEY

Response:

{
  "results": [{
    "geometry": {
      "location": {
        "lat": 27.7070,
        "lng": 85.3241
      }
    },
    "formatted_address": "Kathmandu University, Dhulikhel, Nepal"
  }]
}

3. Maps in Mobile Apps

Maps are the visual interface for location data. The two most popular SDKs are Google Maps SDK and Mapbox.

3.1 Google Maps SDK vs. Mapbox

Feature Google Maps SDK Mapbox
Base Maps Street View, Satellite, Terrain Customizable (e.g., dark mode, outdoor)
3D Buildings Yes (in some regions) Yes (more customizable)
Indoor Maps Limited (e.g., airports) Better for large buildings (e.g., hospitals)
Offline Maps Yes (downloadable) Yes (better compression)
Pricing Free tier (28,500 map loads/month) Free tier (50,000 loads/month)
Best For General navigation, global coverage Custom maps, design flexibility

Example: Daraz Delivery Route Planning Daraz uses Google Maps Directions API to:

  1. Get the customer’s address ({lat, lng}).
  2. Calculate the fastest route to the nearest Daraz warehouse.
  3. Optimize delivery routes for multiple orders (using Directions Matrix API).

3.2 Adding a Map to an Android App

Step 1: Add Dependency (build.gradle)

implementation 'com.google.android.gms:play-services-maps:18.2.0'

Step 2: Add API Key (AndroidManifest.xml)

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_API_KEY" />

Step 3: XML Layout (activity_map.xml)

<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Step 4: Java Code (Add Marker)

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
    .findFragmentById(R.id.map);
mapFragment.getMapAsync(map -> {
    LatLng kuLocation = new LatLng(27.7070, 85.3241);
    map.addMarker(new MarkerOptions()
        .position(kuLocation)
        .title("Kathmandu University"));
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(kuLocation, 15));
});

STATE AFTER EACH STEP (Visual Trace):

gantt
    title Map Initialization Steps
    section Step 1: Dependency Added
    Add Google Maps SDK :a1, 2023-01-01, 1d
    section Step 2: API Key Set
    Configure AndroidManifest :a2, after a1, 1d
    section Step 3: Layout Ready
    Define SupportMapFragment :a3, after a2, 1d
    section Step 4: Marker Added
    Add Marker at KU :a4, after a3, 1d
    section Final State
    Map Shows KU Marker :a5, after a4, 1d

4. Navigation and Directions

Navigation apps (Pathao, Google Maps) use Directions API to calculate routes.

4.1 How Directions API Works

  1. Input: Start ({lat1, lng1}), End ({lat2, lng2}), Mode (DRIVING, WALKING, TRANSIT).
  2. API Call:
    GET https://maps.googleapis.com/maps/api/directions/json?
        origin=27.7172,85.3240&
        destination=27.7070,85.3241&
        mode=walking&
        key=YOUR_API_KEY
    
  3. Output: Polyline (route), distance, duration, steps.
1.22.50.83.1KUTUIntersection ARing Road
Example route network between Kathmandu University (KU) and Tribhuvan University (TU)

Example: NTC Bus Route Optimization NTC’s Nepal Bus Tracker app uses Directions API to:

  1. Show the fastest bus route from Kathmandu to Pokhara.
  2. Overlay real-time traffic data (from Traffic API).
  3. Provide alternative routes if a road is closed.

4.2 Step-by-Step Route Calculation (Mermaid Flowchart)

flowchart TD
    A["User Requests Route\nKU → TU"] --> B["API Call\nDirections API"]
    B --> C["Response:\nPolyline, Steps, Duration"]
    C --> D["Draw Polyline\non Map"]
    D --> E["Add Steps\nas Instructions"]
    E --> F["Update UI\nShow ETA: 20 min"]

JSON Response Example:

{
  "routes": [{
    "overview_polyline": {
      "points": "..." // Encoded polyline
    },
    "legs": [{
      "steps": [{
        "html_instructions": "Head northeast on Dhulikhel Road",
        "distance": { "text": "1.2 km" },
        "duration": { "text": "3 min" }
      }]
    }]
  }]
}

5. Location Permissions and Best Practices

Android requires explicit permissions for location access.

5.1 Permission Types

Permission Scope Runtime Request?
ACCESS_FINE_LOCATION GPS (high accuracy) Yes
ACCESS_COARSE_LOCATION Network (low accuracy) Yes
ACCESS_BACKGROUND_LOCATION Location when app is backgrounded Yes (Android 10+)

Example: Requesting Permissions in Code

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
    != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(
        this,
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
        LOCATION_PERMISSION_REQUEST_CODE
    );
}

5.2 Handling Permission Denials

If the user denies permissions:

  1. Show a fallback (e.g., "Use network location instead").
  2. Explain why the app needs location (e.g., "For accurate delivery tracking").
  3. Use ACCESS_COARSE_LOCATION as a backup.

Example: Pathao’s Permission Handling

  • If GPS is denied, Pathao switches to network location (less accurate but works).
  • If all permissions are denied, it shows a static map with a warning.

6. Offline Maps and Caching

For apps used in rural Nepal (e.g., NTC’s offline bus schedules) or low-connectivity areas, offline maps are critical.

6.1 Downloading Maps (Google Maps SDK)

MapFragment mapFragment = (MapFragment) getFragmentManager()
    .findFragmentById(R.id.map);
mapFragment.getMapAsync(map -> {
    map.setMapStyle(MapStyleOptions.loadRawResourceStyle(
        this, R.raw.offline_map_style));
    OfflineMap offlineMap = new OfflineMap();
    offlineMap.downloadMap(new LatLngBounds(...), new OfflineMapListener() {
        @Override
        public void onDownloadComplete() { /* Ready for offline use */ }
    });
});

6.2 Storing Maps Locally (SQLite + Assets)

  1. Download map tiles (e.g., Kathmandu area) and store in /assets/maps/.
  2. Use SQLite to cache geocoding results for faster access.

Example: Ncell’s Offline Map App

  • Downloads Pokhara city map (50 MB) for offline use.
  • Uses SQLite to store frequently searched locations (e.g., "Lakeside").

7. Real-World Applications

7.1 Pathao (Ride-Hailing)

  • Idea Used: Real-time location tracking (GPS + Fused Location Provider).
  • How: Driver and rider locations update every 5 seconds via Google Maps SDK.
  • Challenge: Balances battery life (GPS off when idle) and accuracy (high when moving).

7.2 eSewa (Service Locator)

  • Idea Used: Geocoding + Reverse Geocoding.
  • How: When you search for "ATM near me," eSewa:
    1. Gets your location ({lat, lng}).
    2. Uses reverse geocoding to find nearby ATMs.
    3. Displays results on a Google Map.

7.3 Daraz (Delivery Optimization)

  • Idea Used: Directions API + Directions Matrix API.
  • How: Daraz calculates:
    • Fastest route from warehouse to customer.
    • Optimal sequence for multiple deliveries (saves fuel).
  • Example: If you order from Daraz Kathmandu, the app may route the delivery driver via Ring Road → Thapathali instead of Balkhu → Thapathali to avoid traffic.

8. Exam Tip

What to Expect in TU/PU Exams

  1. Short Questions (2–5 marks):

    • Define geocoding, reverse geocoding, Fused Location Provider.
    • Difference between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.
    • List two sources of location in Android.
  2. Programming Questions (10–15 marks):

    • Write code to:
      • Request location permissions.
      • Add a marker to Google Maps.
      • Parse a Directions API JSON response.
    • Trace an example: Show the state of a map after adding 3 markers.
  3. Scenario-Based (5–10 marks):

    • "Design a location-based app for NTC bus tracking. Explain how you’d use Google Maps SDK and handle offline scenarios."
    • "A user denies GPS permission in your Pathao-like app. How would you handle it?"
  4. Diagram-Based (5 marks):

    • Draw a sequence diagram for geocoding (user → app → Google Maps API → app).
    • Show the state of a map after:
      • Adding a marker.
      • Drawing a polyline route.

How to Score Full Marks

  • For theory: Use bullet points and tables (like the one comparing GPS vs. Network).
  • For code: Always include:
    1. The code snippet.
    2. A step-by-step trace (e.g., variable values after each API call).
  • For diagrams: Label every arrow and box clearly (e.g., "User requests route" → "Directions API").
  • For real-world examples: Tie answers to Nepali apps (eSewa, Pathao, NTC) or global ones (Google Maps, Uber).

Final Checklist Before Exam

Topic Key Points to Remember
Location Sources GPS (high accuracy, high battery), Network (low accuracy, low battery), Sensor Fusion.
Geocoding Forward (address → coords), Reverse (coords → address). Use Google Maps API.
Google Maps SDK Requires API key, SupportMapFragment, MarkerOptions, Polyline.
Directions API Input: origin, destination, mode. Output: polyline, steps, duration.
Permissions ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION. Always request at runtime.
Offline Maps Download tiles, use SQLite for caching. Example: Ncell’s offline Pokhara map.
Real-World Apps Pathao (real-time tracking), eSewa (geocoding), Daraz (route optimization).

Based on the TU BIM syllabus for Mobile Application Development (IT272), unit 8.

Discussion

Loading…