maps: routing
- Commit
b184b300b5cc0fa1414d95849b8011e3f4c41b9c- Author
- Vayun Mathur <[email protected]>
- When
- 2026-02-04 03:02 UTC (10 months ago)
- Parents
85922db
Diff
maps/src/main/java/com/vayunmathur/maps/RouteService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/RouteService.kt b/maps/src/main/java/com/vayunmathur/maps/RouteService.ktnew file mode 100644index 0000000000..728cf6c03b--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/RouteService.kt@@ -0,0 +1,138 @@+package com.vayunmathur.maps++import com.vayunmathur.maps.ui.SpecificFeature+import io.ktor.client.*+import io.ktor.client.call.*+import io.ktor.client.plugins.contentnegotiation.*+import io.ktor.client.request.*+import io.ktor.client.statement.bodyAsText+import io.ktor.http.*+import io.ktor.serialization.kotlinx.json.*+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import org.maplibre.spatialk.geojson.Position++// --- Request Models ---+@Serializable+data class RoutesRequest(+ val origin: Waypoint,+ val destination: Waypoint,+ val travelMode: String = "DRIVE",+ val routingPreference: String = "TRAFFIC_AWARE",+ val computeAlternativeRoutes: Boolean = false,+ val routeModifiers: RouteModifiers = RouteModifiers(),+ val languageCode: String = "en-US",+ val units: String = "METRIC"+)++@Serializable+data class Waypoint(val location: Location)++@Serializable+data class Location(val latLng: LatLng)++@Serializable+data class LatLng(val latitude: Double, val longitude: Double)++@Serializable+data class RouteModifiers(+ val avoidTolls: Boolean = false,+ val avoidHighways: Boolean = false,+ val avoidFerries: Boolean = false+)++// --- Response Models ---+@Serializable+data class RouteResponse(val routes: List<RouteRes> = emptyList())++@Serializable+data class RouteRes(+ val duration: String,+ val distanceMeters: Int,+ val polyline: Polyline+)++@Serializable+data class Polyline(val encodedPolyline: String)++object RouteService {+ private val client = HttpClient {+ install(ContentNegotiation) {+ json(Json {+ ignoreUnknownKeys = true+ encodeDefaults = true // Important to include default values in JSON+ })+ }+ }++ private const val API_KEY = "AIzaSyBJ2gUeEQ36jbBGLRJUjK1541StDfpBWHI"+ private const val ROUTES_URL = "https://routes.googleapis.com/directions/v2:computeRoutes"++ suspend fun computeRoute(+ features: SpecificFeature.Route,+ userPosition: Position+ ): Route? {+ val originPos = features.from?.position ?: userPosition+ val destPos = features.to?.position ?: userPosition++ val request = RoutesRequest(+ origin = Waypoint(Location(LatLng(originPos.latitude, originPos.longitude))),+ destination = Waypoint(Location(LatLng(destPos.latitude, destPos.longitude)))+ )++ return try {+ val response: RouteResponse = client.post(ROUTES_URL) {+ contentType(ContentType.Application.Json)+ header("X-Goog-Api-Key", API_KEY)+ header("X-Goog-FieldMask", "routes.duration,routes.distanceMeters,routes.polyline.encodedPolyline")+ setBody(request) // Now it knows exactly how to serialize this object+ }.body()++ val routeres = response.routes.firstOrNull() ?: return null+ return Route(routeres.duration, routeres.distanceMeters, decodePolyline(routeres.polyline.encodedPolyline))+ } catch (e: Exception) {+ e.printStackTrace()+ null+ }+ }++ private fun decodePolyline(encoded: String): List<Position> {+ val poly = mutableListOf<Position>()+ var index = 0+ val len = encoded.length+ var lat = 0+ var lng = 0++ while (index < len) {+ var b: Int+ var shift = 0+ var result = 0+ do {+ b = encoded[index++].code - 63+ result = result or (b and 0x1f shl shift)+ shift += 5+ } while (b >= 0x20)+ val dlat = if (result and 1 != 0) (result shr 1).inv() else result shr 1+ lat += dlat++ shift = 0+ result = 0+ do {+ b = encoded[index++].code - 63+ result = result or (b and 0x1f shl shift)+ shift += 5+ } while (b >= 0x20)+ val dlng = if (result and 1 != 0) (result shr 1).inv() else result shr 1+ lng += dlng++ poly.add(Position(lng.toDouble() / 1E5, lat.toDouble() / 1E5))+ }+ return poly+ }+}++data class Route(+ val duration: String,+ val distanceMeters: Int,+ val polyline: List<Position>+)\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 4955f41516..f0cee26218 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -1,16 +1,20 @@ package com.vayunmathur.maps.ui import androidx.activity.compose.BackHandler-import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.BottomSheetScaffold-import androidx.compose.material3.BottomSheetScaffoldState+import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ListItem+import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme-import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.SheetValue import androidx.compose.material3.Text@@ -23,35 +27,26 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.vayunmathur.library.util.readLines+import com.vayunmathur.library.util.round import com.vayunmathur.maps.CountryMap import com.vayunmathur.maps.OSM+import com.vayunmathur.maps.Route+import com.vayunmathur.maps.RouteService import com.vayunmathur.maps.Wikidata import com.vayunmathur.maps.data.OpeningHours-import io.ktor.client.HttpClient-import io.ktor.client.request.get-import io.ktor.client.request.header-import io.ktor.client.statement.bodyAsText-import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch-import kotlinx.coroutines.selects.select-import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive import okio.source import org.maplibre.compose.camera.rememberCameraState-import org.maplibre.compose.expressions.dsl.Feature.get-import org.maplibre.compose.expressions.dsl.all-import org.maplibre.compose.expressions.dsl.asString import org.maplibre.compose.expressions.dsl.const-import org.maplibre.compose.expressions.dsl.eq-import org.maplibre.compose.expressions.dsl.nil-import org.maplibre.compose.expressions.dsl.not+import org.maplibre.compose.expressions.value.LineCap import org.maplibre.compose.layers.FillLayer import org.maplibre.compose.layers.LineLayer import org.maplibre.compose.map.GestureOptions@@ -62,8 +57,6 @@ import org.maplibre.compose.map.RenderOptions import org.maplibre.compose.sources.GeoJsonData import org.maplibre.compose.sources.GeoJsonOptions import org.maplibre.compose.sources.GeoJsonSource-import org.maplibre.compose.sources.Source-import org.maplibre.compose.sources.getBaseSource import org.maplibre.compose.style.BaseStyle import org.maplibre.compose.style.rememberStyleState import org.maplibre.compose.util.ClickResult@@ -71,18 +64,28 @@ import org.maplibre.compose.util.MaplibreComposable import org.maplibre.spatialk.geojson.Feature import org.maplibre.spatialk.geojson.FeatureCollection import org.maplibre.spatialk.geojson.Geometry+import org.maplibre.spatialk.geojson.LineString import org.maplibre.spatialk.geojson.MultiPolygon+import org.maplibre.spatialk.geojson.Point+import org.maplibre.spatialk.geojson.PointGeometry import org.maplibre.spatialk.geojson.Polygon import org.maplibre.spatialk.geojson.Position+import kotlin.time.Duration sealed interface SpecificFeature {+ interface RoutableFeature : SpecificFeature {+ val position: Position+ val name: String+ }+ data class Admin0Label(val iso3166_1: String, val wikipedia: String, val name: String) : SpecificFeature data class Admin1Label(val iso3166_2: String, val wikipedia: String, val name: String) : SpecificFeature- data class Restaurant(val name: String?, val phone: String?, val website: String?, val menu: String?, val openingHours: OpeningHours?): SpecificFeature+ data class Restaurant(override val name: String, val phone: String?, val website: String?, val menu: String?, val openingHours: OpeningHours?,+ override val position: Position): RoutableFeature+ data class Route(val from: RoutableFeature?, val to: RoutableFeature?) : SpecificFeature } typealias Feature1 = Feature<Geometry, JsonObject?>-typealias FeatureCollection1 = FeatureCollection<Geometry, JsonObject?> fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content @@ -104,7 +107,7 @@ suspend fun parse(feature: Feature1): SpecificFeature? { val tags = OSM.getTags(osmID.toLong()) println(properties) println(tags)- SpecificFeature.Restaurant(tags["name"], tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) })+ SpecificFeature.Restaurant(tags["name"] ?: "", tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) }, (geometry as Point).coordinates) } else -> null }@@ -118,7 +121,7 @@ fun MapPage() { LaunchedEffect(Unit) { OSM.initialize(context)- outlineSource = GeoJsonSource("selected-country-geojson", GeoJsonData.Features(FeatureCollection1(listOf(+ outlineSource = GeoJsonSource("selected-country-geojson", GeoJsonData.Features( Feature1(Polygon( coordinates = listOf( listOf(@@ -129,7 +132,9 @@ fun MapPage() { Position(-180.0, -90.0) // Close the ring ) )- ), JsonObject(emptyMap()))))), GeoJsonOptions())+ ), JsonObject(emptyMap()))), GeoJsonOptions())+ routeSource = GeoJsonSource("route-geojson", GeoJsonData.Features(Feature1(+ LineString(listOf(Position(0.0, 0.0),Position(0.0, 0.0))), JsonObject(emptyMap()))), GeoJsonOptions()) } var allowProgrammaticHide by remember { mutableStateOf(false) }@@ -144,6 +149,13 @@ fun MapPage() { allowProgrammaticHide = false } + var route: Route? by remember { mutableStateOf(null) }+ LaunchedEffect(selectedFeature) {+ if(selectedFeature is SpecificFeature.Route) {+ route = RouteService.computeRoute(selectedFeature as SpecificFeature.Route, Position(-118.2806312, 34.0213141))+ }+ }+ val coroutineScope = rememberCoroutineScope() BackHandler(selectedFeature != null) {@@ -153,9 +165,10 @@ fun MapPage() { } } + val camera = rememberCameraState() BottomSheetScaffold({- Box(Modifier.padding(horizontal = 16.dp).padding(bottom = 48.dp, top = 8.dp)) {+ Column(Modifier.padding(horizontal = 16.dp).padding(bottom = 48.dp, top = 8.dp)) { when (val feature = selectedFeature) { is SpecificFeature.Admin0Label -> { Column {@@ -170,36 +183,66 @@ fun MapPage() { } } is SpecificFeature.Restaurant -> {- RestaurantBottomSheet(feature)+ RestaurantBottomSheet(feature) {+ selectedFeature = SpecificFeature.Route(null, feature)+ }+ }+ is SpecificFeature.Route -> {+ if(route != null) {+ val duration = Duration.parse(route!!.duration)+ ListItem({Text(duration.toString())}, supportingContent = {+ Text("${(route!!.distanceMeters/1000.0).round(2)} km")+ })+ } } else -> Unit } } }, Modifier, scaffoldState, (56+(if(scaffoldState.bottomSheetState.isVisible) 40 else 0)).dp) { paddingValues ->- val coroutineScope = rememberCoroutineScope()- val style = rememberStyleState()- Box(Modifier.padding(paddingValues).fillMaxSize()) {+ Box(Modifier.padding(paddingValues)) {+ Scaffold { paddingValues ->+ val coroutineScope = rememberCoroutineScope()+ val style = rememberStyleState()+ Box(Modifier.padding(paddingValues).fillMaxSize()) { - MaplibreMap(Modifier, //BaseStyle.Uri("https://api.protomaps.com/styles/v5/light/en.json?key=15a942f94a739448"),- BaseStyle.Json(LocalContext.current.assets.open("style.json").source().readLines().joinToString("\n")),- camera,- styleState = style,- options = MapOptions(RenderOptions(), GestureOptions.Standard, OrnamentOptions.AllDisabled),- onMapClick = { point, offset ->- coroutineScope.launch {- val features = camera.projection?.queryRenderedFeatures(offset, setOf("places_country", "places_region", "pois")) ?: emptyList()- println("FEATURES ${features.map { it.properties }}")- val listedFeatures = features.mapNotNull { parse(it) }- println("SPECIFIC FEATURES $listedFeatures")- listedFeatures.firstOrNull()?.let {- selectedFeature = it- scaffoldState.bottomSheetState.expand()+ MaplibreMap(Modifier, //BaseStyle.Uri("https://api.protomaps.com/styles/v5/light/en.json?key=15a942f94a739448"),+ BaseStyle.Json(LocalContext.current.assets.open("style.json").source().readLines().joinToString("\n")),+ camera,+ styleState = style,+ options = MapOptions(RenderOptions(), GestureOptions.Standard, OrnamentOptions.AllDisabled),+ onMapClick = { point, offset ->+ coroutineScope.launch {+ val features = camera.projection?.queryRenderedFeatures(offset, setOf("places_country", "places_region", "pois")) ?: emptyList()+ println("FEATURES ${features.map { it.properties }}")+ val listedFeatures = features.mapNotNull { parse(it) }+ println("SPECIFIC FEATURES $listedFeatures")+ listedFeatures.firstOrNull()?.let {+ selectedFeature = it+ scaffoldState.bottomSheetState.expand()+ }+ }+ ClickResult.Pass+ }+ ) {+ MyMapLayers(selectedFeature, route)+ }++ if(selectedFeature is SpecificFeature.Route) {+ Column(Modifier.align(Alignment.TopCenter).padding(16.dp).fillMaxWidth()) {+ Card(shape = verticalShape(0, 2)) {+ ListItem({+ Text((selectedFeature as SpecificFeature.Route).from?.name ?: "Your location")+ }, colors = ListItemDefaults.colors(Color.Transparent))+ }+ Spacer(Modifier.height(2.dp))+ Card(shape = verticalShape(1, 2)) {+ ListItem({+ Text((selectedFeature as SpecificFeature.Route).to?.name ?: "Your location")+ }, colors = ListItemDefaults.colors(Color.Transparent))+ } } }- ClickResult.Pass }- ) {- MyMapLayers(selectedFeature) } } }@@ -228,10 +271,11 @@ fun createInvertedMask(countryFeature: Feature1): Feature1 { } lateinit var outlineSource: GeoJsonSource+lateinit var routeSource: GeoJsonSource @Composable @MaplibreComposable-fun MyMapLayers(selectedFeature: SpecificFeature?) {+fun MyMapLayers(selectedFeature: SpecificFeature?, route: Route?) { val context = LocalContext.current when (selectedFeature) { is SpecificFeature.Admin0Label -> {@@ -261,6 +305,19 @@ fun MyMapLayers(selectedFeature: SpecificFeature?) { color = const(Color.Red) ) }++ is SpecificFeature.Route -> {+ if(route != null) {+ LaunchedEffect(route) {+ routeSource.setData(GeoJsonData.Features(FeatureCollection(listOf(Feature1(+ LineString(route.polyline), JsonObject(emptyMap())+ )))))+ }+ LineLayer("route", routeSource,+ color = const(Color.Blue), width = const(8.dp), cap = const(LineCap.Round))+ }+ }+ else -> Unit } }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.ktindex 7e32f1e1dc..41c99d6f26 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.kt@@ -5,9 +5,12 @@ import android.content.Intent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon@@ -21,6 +24,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape@@ -45,11 +49,15 @@ fun goto(context: Context, uri: String) { } @Composable-fun RestaurantBottomSheet(feature: SpecificFeature.Restaurant) {+fun RestaurantBottomSheet(feature: SpecificFeature.Restaurant, requestDirections: () -> Unit) { val context = LocalContext.current Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text(feature.name ?: "", style = MaterialTheme.typography.titleLarge)+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(feature.name ?: "", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))+ Button({requestDirections()}) { Text("Directions") }+ } feature.openingHours?.let {+ Spacer(Modifier.height(8.dp)) var showDetails by remember { mutableStateOf(false) } val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())