Nearest Branch

Finding the Nearest BookNest Branch

BookNest has three (fictional) branches around San Jose. Location.distanceBetween() measures on the WGS84 ellipsoid, so the nearest is a minBy:

location/Branches.kt: branches and the nearest oneKotlin
data class Branch(val name: String, val lat: Double, val lng: Double)
val branches = listOf(
  Branch("BookNest Palo Alto", 37.4443, -122.1598),
  Branch("BookNest Mountain View", 37.3894, -122.0819),
  Branch("BookNest San Jose", 37.3337, -121.8907),
)
fun nearestBranch(here: Location): Pair<Branch, Float> = branches
  .map { b ->
    val result = FloatArray(1)
    Location.distanceBetween(here.latitude, here.longitude, b.lat, b.lng, result)
    b to result[0]
  }
  .minBy { it.second }

NearestBranchScreen recomputes it for the one-shot fix and every update.

The nearest-branch screen before and after the emulator's position moved
The nearest-branch screen before and after the emulator's position moved

For many shops, ask the server for "branches near me"; for a map, the Maps SDK's maps-compose library draws one in Compose 234 (it needs an API key and billing account, so this book stops at distances).