Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 104 ยท Building a Real UI

Google Maps in Android: Markers, Polylines and Distance

Use Google Maps in an Android app: API key and SHA-1, the Maps SDK and Compose, markers, camera, polylines, map types, search, distance and live tracking, with runnable geometry stand-ins.

A map is one of the most requested screens in a mobile app: delivery tracking, store finders, ride sharing, fitness routes. On Android the standard tool is the Maps SDK for Android, which draws Google Maps inside your app and lets you add markers, lines and shapes, move the camera and react to taps. Around it sit two other pieces: location (where is the user?) and geometry (how far apart are two points, how long is a route?).

The Maps SDK and the Google services behind it cannot run on this site, so the Android code is read-only. The geometry, however, is plain math, so the TryIts are real, runnable Kotlin: great-circle distance, route length, bounding boxes and a polyline decoder. Those are the same calculations that production apps do on top of the SDK.

The big picture

flowchart LR
    A["Your app"] --> M["Maps SDK<br/>draws the map"]
    A --> L["Fused location<br/>where is the user"]
    A --> P["Places and Routes APIs<br/>search and directions"]
    M --> G["Google Cloud project<br/>API key and billing"]
    P --> G

The map, the user's location and search or directions are three separate services; the API key ties them to your Google Cloud project.

Getting an API key

  1. In the Google Cloud console, create a project and enable Maps SDK for Android (and Places or Routes if you need them). A billing account is required, though a free monthly usage allowance usually covers development.
  2. Create an API key. Immediately restrict it: choose "Android apps", then add your package name and the SHA-1 certificate fingerprint of your signing key. An unrestricted key in a public repository will be abused and billed to you.
  3. You need a fingerprint for each key you sign with, so add both your debug key and your release (or Play App Signing) key.

You read the SHA-1 and SHA-256 fingerprints from Gradle or the command line:

Terminal
# read-only example: print the debug keystore fingerprints
./gradlew signingReport

# or with keytool (the default debug keystore lives in ~/.android)
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

Do not commit the key. The Secrets Gradle Plugin keeps it in local.properties and injects it into the manifest:

XML
<!-- read-only example: AndroidManifest.xml, inside <application> -->
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}" />

See Signing and release builds for how your debug and release keys differ, and Security on Android for key handling.

Showing a map

In Compose, the Maps Compose library gives you a GoogleMap composable. The camera is state you can remember and move.

Kotlin
// read-only example: Maps Compose
// build.gradle.kts: implementation("com.google.maps.android:maps-compose:<version>")
@Composable
fun StoreMap(stores: List<Store>) {
    val berlin = LatLng(52.52, 13.405)
    val cameraState = rememberCameraPositionState {
        position = CameraPosition.fromLatLngZoom(berlin, 11f)
    }

    GoogleMap(
        modifier = Modifier.fillMaxSize(),
        cameraPositionState = cameraState,
        properties = MapProperties(mapType = MapType.NORMAL),
        uiSettings = MapUiSettings(zoomControlsEnabled = true)
    ) {
        stores.forEach { store ->
            Marker(
                state = MarkerState(position = LatLng(store.lat, store.lng)),
                title = store.name,
                snippet = store.address,
                onClick = { /* return true if you handled the click yourself */ false }
            )
        }
    }
}

In the View system the map is a SupportMapFragment in your layout; you call getMapAsync and receive a GoogleMap object in onMapReady:

Kotlin
// read-only example: View system
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync { googleMap ->
    val sydney = LatLng(-33.868, 151.209)
    googleMap.addMarker(MarkerOptions().position(sydney).title("Sydney"))
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12f))
}

Coordinates are LatLng(latitude, longitude): latitude first. Mixing the order puts your marker in the ocean.

Map types and UI settings

MapType chooses the base look: NORMAL (roads and labels), SATELLITE (photos), TERRAIN (relief), HYBRID (satellite with labels) and NONE (a blank canvas for custom tiles). MapUiSettings toggles zoom buttons, compass, the "my location" button, tilt and rotation gestures. A JSON map style can recolor roads and hide points of interest, for instance a dark style for night mode.

Markers

A marker has a position, a title and snippet shown in its info window, and an icon. You can use a custom icon (a vector converted to a BitmapDescriptor) so your pins look like your brand, and you can make markers draggable.

Handling a tap on a marker (onClick in Compose, setOnMarkerClickListener in Views) is the place to open a detail sheet. For hundreds of points, use marker clustering from the Maps Utils library so the map stays readable and fast. When markers come from a backend, they are just data: load a list, map it to Markers and let state changes update them. For live data (a courier moving) you update a MarkerState.position rather than adding new markers.

Fitting all markers on screen

To show every marker at a sensible zoom, build a LatLngBounds and move the camera to it with padding: CameraUpdateFactory.newLatLngBounds(bounds, 100). The computation of the bounds is simple enough to run here.

Kotlin Bounding box and center of markers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This is what LatLngBounds.Builder().include(...) does. The real class also handles longitude wrap-around at the 180th meridian, which this stand-in does not.

Drawing a polyline

A polyline is an ordered list of points drawn as a line; a polygon is a closed area; a circle has a center and radius. Routes from the Directions or Routes API come as an encoded polyline, a compact string that you decode into points and pass to the map:

Kotlin
// read-only example
Polyline(
    points = routePoints,       // List<LatLng>
    color = Color(0xFF1A73E8),
    width = 12f
)

The encoding turns each coordinate delta into base-64-like ASCII, which is why a route of thousands of points fits in a short response. Decoding is a good exercise in bit work, and it runs fine here.

Kotlin Decode an encoded polyline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The result is three points near the US west coast, the standard example for this format. Notice the trick: each point is stored as a difference from the previous one, and only the small differences are encoded.

Distance between two locations

The Earth is (nearly) a sphere, so the straight-line distance on the map is wrong for long ranges. The haversine formula gives the great-circle distance. On Android you can also call Location.distanceBetween(...) or location1.distanceTo(location2), which use a more exact ellipsoid model, but the haversine result is within about half a percent for most uses.

Kotlin Haversine distance and route length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

For a distance by road you cannot use geometry at all: ask the Routes API (or Distance Matrix), which understands roads and traffic.

Where is the user? Location and tracking

The map's blue dot ("my location layer") needs the location permission (see Runtime permissions): ask for ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION together and respect a coarse-only answer. Then set isMyLocationEnabled = true in MapProperties.

For your own logic (center the map on the user, record a run), use the Fused Location Provider, which blends GPS, Wi-Fi and cell signals and manages battery:

Kotlin
// read-only example: a Flow of locations
fun locationUpdates(client: FusedLocationProviderClient): Flow<Location> = callbackFlow {
    val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5_000L).build()
    val callback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult) {
            result.lastLocation?.let { trySend(it) }
        }
    }
    client.requestLocationUpdates(request, callback, Looper.getMainLooper())
    awaitClose { client.removeLocationUpdates(callback) }   // always stop updates
}

To draw a live track, collect this flow, append each location to a list in your ViewModel and show the list as a Polyline. Tracking while the app is in the background needs a foreground service with a location type and the background-location permission, which Play reviews strictly (see Services and notifications).

Search on the map

Two options: a plain SearchView that geocodes the text with Geocoder (turns an address into a LatLng; the call is blocking, so run it off the main thread), or the Places SDK, which offers an autocomplete widget and richer results. After you have a LatLng, search is just "move the camera and add a marker":

Kotlin
// read-only example
scope.launch {
    val results = withContext(Dispatchers.IO) { geocoder.getFromLocationName(query, 1) }
    results?.firstOrNull()?.let {
        cameraState.animate(CameraUpdateFactory.newLatLngZoom(LatLng(it.latitude, it.longitude), 14f))
    }
}

Common mistakes

  • Shipping an unrestricted API key or committing it to a public repository.
  • A blank grey map: the key is missing, billing is off, the SHA-1 or package name does not match the restriction, or the SDK is not enabled.
  • Latitude and longitude swapped.
  • Updating location at maximum accuracy forever; stop updates when the screen is not visible.
  • Adding thousands of markers without clustering.
  • Doing geocoding on the main thread.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pair of values do you add to an API key restriction for an Android app?

    Restricting by package name plus signing-certificate fingerprint means only your signed app can use the key.
  2. 2. What is the correct order of the arguments of LatLng?

    LatLng(latitude, longitude). Swapping them moves the point to the wrong place on the globe.
  3. 3. Why use the haversine formula instead of Pythagoras on latitude and longitude values?

    Haversine is a great-circle distance on a sphere. It does not know about roads; use the Routes API for road distance.
  4. 4. How are most route polylines delivered by a directions API?

    Encoded polylines store the difference from the previous point in compact ASCII, which keeps responses small.

Summary

  • Get a Maps API key in a Google Cloud project and restrict it with your package name and SHA-1 fingerprints.
  • Use GoogleMap in Compose or SupportMapFragment in Views; coordinates are LatLng(lat, lng).
  • Markers, polylines, polygons and circles are the building blocks; cluster big marker sets and fit the camera with LatLngBounds.
  • Distance on a sphere uses haversine; road distance needs a routing API.
  • Use the Fused Location Provider for the user's position, stop updates when not needed and request permissions properly.

Next: Lottie, shimmer and motion.