maps: downloadable maps
- Commit
bf6d59dc3ffbd596103d9c7753add5bf95f87c85- Author
- Vayun Mathur <[email protected]>
- When
- 2026-02-06 02:21 UTC (10 months ago)
- Parents
63ed50e
Diff
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 96cf728e77..d97862494d 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -24,5 +24,6 @@ dependencies { // room implementation(libs.androidx.room.runtime) implementation(libs.androidx.room.ktx)+ implementation(libs.androidx.navigation3.runtime) ksp(libs.androidx.room.compiler) }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/CountryMap.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/CountryMap.kt b/maps/src/main/java/com/vayunmathur/maps/CountryMap.ktindex f8726784f5..cd1976ebe1 100644--- a/maps/src/main/java/com/vayunmathur/maps/CountryMap.kt+++ b/maps/src/main/java/com/vayunmathur/maps/CountryMap.kt@@ -1,7 +1,7 @@ package com.vayunmathur.maps import android.content.Context-import com.vayunmathur.maps.ui.Feature1+import com.vayunmathur.maps.data.Feature1 import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex fe4c5d1ff0..9292105000 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -27,14 +27,19 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.core.net.toUri+import androidx.navigation3.runtime.NavKey import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.buildDatabase+import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.maps.data.TagDatabase+import com.vayunmathur.maps.ui.DownloadedMapsPage import com.vayunmathur.maps.ui.MapPage import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking+import kotlinx.serialization.Serializable import java.io.File fun ensurePmtilesReady(context: Context): String {@@ -64,7 +69,7 @@ class MainActivity : ComponentActivity() { val downloadedState by ds.getLongState("downloaded") val isDownloaded = downloadedState == 2L if(isDownloaded) {- MapPage(ds, db)+ Navigation(ds, db) } else { DownloadPage(ds, db) }@@ -73,6 +78,28 @@ class MainActivity : ComponentActivity() { } } +@Serializable+sealed interface Route: NavKey {+ @Serializable+ data object MapPage: Route+ @Serializable+ data object DownloadedMapsPage: Route+}++@Composable+fun Navigation(ds: DataStoreUtils, db: TagDatabase) {+ val backStack = rememberNavBackStack<Route>(Route.MapPage)+ val context = LocalContext.current+ MainNavigation(backStack) {+ entry<Route.MapPage> {+ MapPage(backStack, ds, db)+ }+ entry<Route.DownloadedMapsPage> {+ DownloadedMapsPage(backStack)+ }+ }+}+ @Composable fun DownloadPage(ds: DataStoreUtils, db: TagDatabase) { val context = LocalContext.current
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.ktindex e9251be55a..67594d12a6 100644--- a/maps/src/main/java/com/vayunmathur/maps/RouteService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/RouteService.kt@@ -1,6 +1,6 @@ package com.vayunmathur.maps -import com.vayunmathur.maps.ui.SpecificFeature+import com.vayunmathur.maps.data.SpecificFeature import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.plugins.contentnegotiation.*
maps/src/main/java/com/vayunmathur/maps/TransitRoute.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/TransitRoute.kt b/maps/src/main/java/com/vayunmathur/maps/TransitRoute.ktindex 6685ab3fa6..f35027f9d3 100644--- a/maps/src/main/java/com/vayunmathur/maps/TransitRoute.kt+++ b/maps/src/main/java/com/vayunmathur/maps/TransitRoute.kt@@ -1,6 +1,6 @@ package com.vayunmathur.maps -import com.vayunmathur.maps.ui.SpecificFeature+import com.vayunmathur.maps.data.SpecificFeature import org.maplibre.spatialk.geojson.Position import kotlin.time.Clock import kotlin.time.Duration@@ -44,7 +44,7 @@ data class TransitRoute(val steps: List<Step>, override val duration: Duration = } else if(steps.last() is Step.WalkStep) { val lastStep = steps.last() as Step.WalkStep val secondLastStep = steps[steps.size - 2] as Step.TransitStep- return secondLastStep.arrivalTime+ return secondLastStep.arrivalTime + lastStep.duration } else { val lastStep = steps.last() as Step.TransitStep return lastStep.arrivalTime@@ -53,7 +53,7 @@ data class TransitRoute(val steps: List<Step>, override val duration: Duration = companion object { suspend fun computeRoute(features: SpecificFeature.Route,- userPosition: Position): TransitRoute {+ userPosition: Position): TransitRoute { val res = RouteService.computeRoute(features, userPosition, RouteService.TravelMode.TRANSIT)!! val steps = res.step.map { if(it.travelMode == RouteService.TravelMode.WALK) {
maps/src/main/java/com/vayunmathur/maps/ZoneDownloadManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ZoneDownloadManager.kt b/maps/src/main/java/com/vayunmathur/maps/ZoneDownloadManager.ktnew file mode 100644index 0000000000..21b3411aa6--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ZoneDownloadManager.kt@@ -0,0 +1,144 @@+package com.vayunmathur.maps++import android.app.DownloadManager+import android.content.Context+import android.net.Uri+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.conflate+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOn+import java.io.File+import androidx.core.net.toUri++class ZoneDownloadManager(private val context: Context) {+ private val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager++ enum class ZoneStatus { NOT_STARTED, DOWNLOADING, FINISHED }++ /**+ * A Flow that emits a Map of all zones currently being downloaded.+ * Key: Zone ID, Value: Progress (0.0 to 1.0).+ * Statuses included: PENDING, RUNNING, and PAUSED.+ */+ fun getDownloadingZonesFlow(): Flow<Map<Int, Float>> = flow {+ while (true) {+ val progressMap = mutableMapOf<Int, Float>()++ // Query for any task that isn't finished or failed+ val query = DownloadManager.Query().setFilterByStatus(+ DownloadManager.STATUS_RUNNING or+ DownloadManager.STATUS_PENDING or+ DownloadManager.STATUS_PAUSED+ )++ val cursor = downloadManager.query(query)+ while (cursor.moveToNext()) {+ val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+ // Extract Zone ID from title: "Map Zone 52" -> 52+ if (title.startsWith("Map Zone ")) {+ val zoneId = title.removePrefix("Map Zone ").toIntOrNull()+ if (zoneId != null) {+ val downloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))+ val total = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))++ val progress = if (total > 0) downloaded.toFloat() / total.toFloat() else 0f+ progressMap[zoneId] = progress+ }+ }+ }+ cursor.close()++ emit(progressMap)+ delay(1000) // Poll faster (1s) for progress updates+ }+ }+ .distinctUntilChanged()+ .flowOn(Dispatchers.IO)++ /**+ * Deletes a zone file and cancels any active downloads for that zone.+ */+ fun deleteZone(zoneId: Int) {+ // 1. Cancel active or pending downloads in the system+ val query = DownloadManager.Query()+ val cursor = downloadManager.query(query)+ while (cursor.moveToNext()) {+ val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+ if (title == "Map Zone $zoneId") {+ val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))+ downloadManager.remove(id) // This stops the download and removes the system entry+ }+ }+ cursor.close()++ // 2. Remove the file from disk+ val file = File(context.getExternalFilesDir(null), "zone_$zoneId.pmtiles")+ if (file.exists()) {+ file.delete()+ }+ }++ fun getDownloadedZonesFlow(): Flow<List<Int>> = flow {+ while (true) {+ emit(getDownloadedZones())+ delay(2000) // Poll every 2 seconds+ }+ }+ .distinctUntilChanged() // Only emit if the list actually changes+ .conflate() // Drop intermediate updates if the UI is slow+ .flowOn(Dispatchers.IO) // Run the disk/DB checks on a background thread++ fun getDownloadedZones(): List<Int> {+ val filesDir = context.getExternalFilesDir(null) ?: return emptyList()++ // We scan the grid 0-63. This is faster than a full regex file list scan+ // and ensures we only return valid zone IDs.+ return (0..63).filter { zoneId ->+ getZoneStatus(zoneId) == ZoneStatus.FINISHED+ }+ }++ fun getZoneStatus(zoneId: Int): ZoneStatus {+ val file = File(context.getExternalFilesDir(null), "zone_$zoneId.pmtiles")++ val query = DownloadManager.Query()+ val cursor = downloadManager.query(query)+ var foundStatus: ZoneStatus? = null++ while (cursor.moveToNext()) {+ val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+ if (title == "Map Zone $zoneId") {+ val systemStatus = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))+ foundStatus = when (systemStatus) {+ DownloadManager.STATUS_SUCCESSFUL -> if (file.exists()) ZoneStatus.FINISHED else ZoneStatus.NOT_STARTED+ DownloadManager.STATUS_RUNNING, DownloadManager.STATUS_PAUSED, DownloadManager.STATUS_PENDING -> ZoneStatus.DOWNLOADING+ DownloadManager.STATUS_FAILED -> {+ if (file.exists()) file.delete() // Clean up ghost file+ ZoneStatus.NOT_STARTED+ }+ else -> ZoneStatus.NOT_STARTED+ }+ break+ }+ }+ cursor.close()++ if (foundStatus != null) return foundStatus+ return if (file.exists()) ZoneStatus.FINISHED else ZoneStatus.NOT_STARTED+ }++ fun startDownload(zoneId: Int) {+ val url = "https://data.vayunmathur.com/zone_$zoneId.pmtiles"+ val request = DownloadManager.Request(url.toUri())+ .setTitle("Map Zone $zoneId")+ .setDescription("Downloading high-detail offline map")+ .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)+ .setDestinationInExternalFilesDir(context, null, "zone_$zoneId.pmtiles")+ .setAllowedOverMetered(true)++ downloadManager.enqueue(request)+ }+}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktnew file mode 100644index 0000000000..f2b0e54984--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -0,0 +1,51 @@+package com.vayunmathur.maps.data++import com.vayunmathur.maps.OSM+import com.vayunmathur.maps.Wikidata+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonPrimitive+import org.maplibre.spatialk.geojson.Feature+import org.maplibre.spatialk.geojson.Geometry+import org.maplibre.spatialk.geojson.Point+import org.maplibre.spatialk.geojson.Position++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(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?>++fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content++suspend fun parse(feature: Feature1): SpecificFeature? {+ val id = feature.id?.jsonPrimitive?.content?.toULong() ?: 0uL+ val osmID = id and ((1uL shl 44) - 1uL)+ val geometry = feature.geometry+ val properties = feature.properties ?: return null+ return when(properties.string("kind")) {+ "country" -> {+ val wiki = Wikidata.get(properties.string("wikidata")!!)+ SpecificFeature.Admin0Label(wiki.getProperty("P297")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)+ }+ "region" -> {+ val wiki = Wikidata.get(properties.string("wikidata")!!)+ SpecificFeature.Admin1Label(wiki.getProperty("P300")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)+ }+ "restaurant", "fast_food", "cafe", "bar" -> {+ 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) }, (geometry as Point).coordinates)+ }+ else -> null+ }+}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/DownloadedMapsPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DownloadedMapsPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DownloadedMapsPage.ktnew file mode 100644index 0000000000..c06a8da012--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DownloadedMapsPage.kt@@ -0,0 +1,66 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.IconButton+import androidx.compose.material3.ListItem+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.navigation3.runtime.NavBackStack+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.maps.Route+import com.vayunmathur.maps.ZoneDownloadManager++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DownloadedMapsPage(backStack: NavBackStack<Route>) {+ val context = LocalContext.current+ val zoneManager = remember { ZoneDownloadManager(context) }+ val downloadedMaps by zoneManager.getDownloadedZonesFlow().collectAsState(initial = emptyList())+ val downloadingZones by zoneManager.getDownloadingZonesFlow().collectAsState(initial = emptyMap())+ Scaffold(topBar = {+ TopAppBar(title = { Text("Downloaded Maps") }, navigationIcon = {+ IconNavigation(backStack)+ })+ }) { paddingValues ->+ Column(Modifier.padding(paddingValues)) {+ LazyColumn() {+ item {+ Text("Downloading Zones:", Modifier.padding(horizontal = 16.dp))+ }+ items(downloadingZones.entries.toList(), {it.key}) {+ ListItem({+ Text("Zone ${it.key}")+ }, trailingContent = {+ Text("${(it.value * 100).toInt()}%")+ })+ }+ item {+ Text("Downloaded Zones:", Modifier.padding(horizontal = 16.dp))+ }+ items(downloadedMaps, {it}) {+ ListItem({+ Text("Zone $it")+ }, trailingContent = {+ IconButton({+ zoneManager.deleteZone(it)+ }) {+ Text("Delete")+ }+ })+ }+ }+ }+ }+}\ 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 2cd55ca5e1..e822b42ff4 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -1,5 +1,6 @@ package com.vayunmathur.maps.ui +import android.content.Context import androidx.activity.compose.BackHandler import androidx.compose.foundation.Canvas import androidx.compose.foundation.background@@ -26,6 +27,7 @@ import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon+import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme@@ -37,6 +39,8 @@ import androidx.compose.material3.SheetValue import androidx.compose.material3.Surface import androidx.compose.material3.Tab import androidx.compose.material3.Text+import androidx.compose.material3.TopAppBar+import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.rememberBottomSheetScaffoldState import androidx.compose.material3.rememberStandardBottomSheetState import androidx.compose.runtime.Composable@@ -57,6 +61,7 @@ import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PaintingStyle.Companion.Stroke import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource@@ -64,6 +69,8 @@ import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.core.graphics.toColor import androidx.core.graphics.toColorInt+import androidx.navigation3.runtime.NavBackStack+import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.readLines import com.vayunmathur.library.util.round@@ -71,12 +78,19 @@ import com.vayunmathur.maps.CountryMap import com.vayunmathur.maps.FrameworkLocationManager import com.vayunmathur.maps.OSM2 import com.vayunmathur.maps.OSM+import com.vayunmathur.maps.Route import com.vayunmathur.maps.RouteService import com.vayunmathur.maps.TransitRoute import com.vayunmathur.maps.Wikidata+import com.vayunmathur.maps.ZoneDownloadManager import com.vayunmathur.maps.data.OpeningHours+import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.TagDatabase+import com.vayunmathur.maps.data.parse import com.vayunmathur.maps.ensurePmtilesReady+import com.vayunmathur.maps.ui.components.BottomSheetContent+import com.vayunmathur.maps.ui.components.MyMapLayers+import com.vayunmathur.maps.ui.components.UserIcon import kotlinx.coroutines.launch import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone@@ -97,6 +111,7 @@ import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject import okio.source import org.maplibre.compose.camera.CameraPosition+import org.maplibre.compose.camera.CameraState import org.maplibre.compose.camera.rememberCameraState import org.maplibre.compose.expressions.ast.Expression import org.maplibre.compose.expressions.dsl.const@@ -131,116 +146,113 @@ 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 java.io.File import kotlin.time.Duration -sealed interface SpecificFeature {- interface RoutableFeature : SpecificFeature {- val position: Position- val name: String- }+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun MapPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, db: TagDatabase) {+ var selectedFeature by remember { mutableStateOf<SpecificFeature?>(null) }+ val context = LocalContext.current+ val coroutineScope = rememberCoroutineScope()+ val zoneManager = remember { ZoneDownloadManager(context) } - 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(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-}+ // --- ZONE DOWNLOAD STATE ---+ val camera = rememberCameraState(CameraPosition(target = Position(-118.243683,34.052235), zoom = 5.0))++ val activeZone = remember(camera.position) {+ calculateZoneId(+ camera.position.target.latitude,+ camera.position.target.longitude,+ camera.position.zoom.toFloat()+ )+ } -typealias Feature1 = Feature<Geometry, JsonObject?>+ val hybridUrl = remember(activeZone) {+ val remoteUrl = "pmtiles://https://demo-bucket.protomaps.com/v4.pmtiles" -fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content+ if (activeZone == null) return@remember remoteUrl -suspend fun parse(feature: Feature1): SpecificFeature? {- val id = feature.id?.jsonPrimitive?.content?.toULong() ?: 0uL- val osmID = id and ((1uL shl 44) - 1uL)- val geometry = feature.geometry- val properties = feature.properties ?: return null- return when(properties.string("kind")) {- "country" -> {- val wiki = Wikidata.get(properties.string("wikidata")!!)- SpecificFeature.Admin0Label(wiki.getProperty("P297")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)- }- "region" -> {- val wiki = Wikidata.get(properties.string("wikidata")!!)- SpecificFeature.Admin1Label(wiki.getProperty("P300")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)- }- "restaurant", "fast_food", "cafe" -> {- 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) }, (geometry as Point).coordinates)+ val localFile = File(context.getExternalFilesDir(null), "zone_$activeZone.pmtiles")+ val x = if (zoneManager.getZoneStatus(activeZone) == ZoneDownloadManager.ZoneStatus.FINISHED) {+ "pmtiles://file://${localFile.absolutePath}"+ } else {+ remoteUrl }- else -> null+ println("URL: $x")+ x }-} -@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun MapPage(ds: DataStoreUtils, db: TagDatabase) {- var selectedFeature by remember { mutableStateOf<SpecificFeature?>(null) }- val context = LocalContext.current+ val json = remember(hybridUrl) {+ patchStyleForHybrid(+ context.assets.open("style.json").source().readLines().joinToString("\n"),+ ensurePmtilesReady(context),+ hybridUrl+ )+ } - val locationManager = remember { FrameworkLocationManager(context) }+ var dismissedZone by remember { mutableStateOf<Int?>(null) }+ var showDownloadDialog by remember { mutableStateOf(false) }++ // Zone Prompting Logic+ LaunchedEffect(activeZone) {+ if (activeZone != null && activeZone != dismissedZone) {+ val status = zoneManager.getZoneStatus(activeZone)++ // Only prompt if the user hasn't started the download yet+ if (status == ZoneDownloadManager.ZoneStatus.NOT_STARTED) {+ showDownloadDialog = true+ }+ }+ } + // --- LOCATION & OSM INITIALIZATION ---+ val locationManager = remember { FrameworkLocationManager(context) } var userPosition by remember { mutableStateOf(Position(0.0, 0.0)) } var userBearing by remember { mutableStateOf(0f) }+ DisposableEffect(Unit) { val listener = locationManager.startUpdates { position, bearing -> userPosition = position userBearing = bearing }-- onDispose {- locationManager.stopUpdates(listener)- }+ onDispose { locationManager.stopUpdates(listener) } } LaunchedEffect(Unit) { OSM.initialize(context)- OSM2.init(context, ds,db)- println("SUBWAY SEARCH")- println(OSM2.search("Galero Grill").map{- OSM.getTags(it)- })- outlineSource = GeoJsonSource("selected-country-geojson", GeoJsonData.Features(- Feature1(Polygon(- coordinates = listOf(- listOf(- Position(-180.0, -90.0),- Position(180.0, -90.0),- Position(180.0, 90.0),- Position(-180.0, 90.0),- Position(-180.0, -90.0) // Close the ring- )- )- ), 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) }-- val scaffoldState = rememberBottomSheetScaffoldState(rememberStandardBottomSheetState(SheetValue.Hidden, {- it != SheetValue.Hidden || allowProgrammaticHide- }, false))-- suspend fun hide() {- allowProgrammaticHide = true- scaffoldState.bottomSheetState.hide()- allowProgrammaticHide = false+ OSM2.init(context, ds, db)+ // Debug search example+ println("SUBWAY SEARCH: ${OSM2.search("Galero Grill").map { OSM.getTags(it) }}") } + // --- ROUTE COMPUTATION --- var route: Map<RouteService.TravelMode, RouteService.RouteType>? by remember { mutableStateOf(null) } LaunchedEffect(selectedFeature) { if(selectedFeature is SpecificFeature.Route) { route = RouteService.TravelMode.entries.associateWith {- if(it == RouteService.TravelMode.TRANSIT) return@associateWith TransitRoute.computeRoute(selectedFeature as SpecificFeature.Route, userPosition)- RouteService.computeRoute(selectedFeature as SpecificFeature.Route, userPosition, it)!!+ if(it == RouteService.TravelMode.TRANSIT) {+ TransitRoute.computeRoute(selectedFeature as SpecificFeature.Route, userPosition)+ } else {+ RouteService.computeRoute(selectedFeature as SpecificFeature.Route, userPosition, it)!!+ } } } } - val coroutineScope = rememberCoroutineScope()+ // --- UI & BOTTOM SHEET STATE ---+ var allowProgrammaticHide by remember { mutableStateOf(false) }+ val scaffoldState = rememberBottomSheetScaffoldState(+ rememberStandardBottomSheetState(SheetValue.Hidden, {+ it != SheetValue.Hidden || allowProgrammaticHide+ }, false)+ )++ suspend fun hide() {+ allowProgrammaticHide = true+ scaffoldState.bottomSheetState.hide()+ allowProgrammaticHide = false+ } BackHandler(selectedFeature != null) { coroutineScope.launch {@@ -251,368 +263,138 @@ fun MapPage(ds: DataStoreUtils, db: TagDatabase) { var selectedRouteType by remember { mutableStateOf(RouteService.TravelMode.DRIVE) } - val camera = rememberCameraState(CameraPosition(target = Position(-118.243683,34.052235), zoom = 5.0))+ // --- RENDER --- BottomSheetScaffold({ Column(Modifier.padding(horizontal = 16.dp).padding(bottom = 48.dp, top = 8.dp)) {- when (val feature = selectedFeature) {- is SpecificFeature.Admin0Label -> {- Column {- Text(feature.name, style = MaterialTheme.typography.titleLarge)- Text(feature.wikipedia, style = MaterialTheme.typography.bodyMedium)- }- }- is SpecificFeature.Admin1Label -> {- Column {- Text(feature.name, style = MaterialTheme.typography.titleLarge)- Text(feature.wikipedia, style = MaterialTheme.typography.bodyMedium)- }- }- is SpecificFeature.Restaurant -> {- RestaurantBottomSheet(feature) {- selectedFeature = SpecificFeature.Route(null, feature)+ BottomSheetContent(selectedFeature, { selectedFeature = it }, route, selectedRouteType, { selectedRouteType = it })+ }+ }, Modifier, scaffoldState, 170.dp) { paddingValues ->+ Scaffold(Modifier.padding(top = paddingValues.calculateTopPadding()), topBar = {+ TopAppBar({}, actions = {+ Card {+ IconButton({+ backStack.add(Route.DownloadedMapsPage)+ }) {+ IconSettings() } }- is SpecificFeature.Route -> {- if(route != null) {- Column {- PrimaryTabRow(route!!.entries.indexOfFirst { it.key == selectedRouteType }) {- route!!.entries.forEach { it ->- Tab(- selectedRouteType == it.key,- { selectedRouteType = it.key }) {- Text(- it.key.name.lowercase()- .replaceFirstChar { it.uppercase() })- }- }- }- val route = route!![selectedRouteType]!!- ListItem({ Text(route.duration.toString()) }, supportingContent = {- Text("${(route.distanceMeters / 1000.0).round(2)} km")- })- Spacer(Modifier.height(8.dp))- Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(2.dp)) {- if(route is TransitRoute) {- val TIME_FORMAT = LocalTime.Format {- amPmHour(Padding.NONE)- chars(":")- minute()- amPmMarker(" AM", " PM")- }- Card(shape = verticalShape(0, 2)) {- ListItem({- val origin = (selectedFeature as SpecificFeature.Route).from?.name ?: "Your location"- Text(origin)- }, trailingContent = {- Text(route.startTime().toLocalDateTime(TimeZone.currentSystemDefault()).time.format(TIME_FORMAT))- })- }- route.steps.forEachIndexed { idx, it ->- Card() {- when(it) {- is TransitRoute.Step.WalkStep -> {- ListItem({- Text("Walk ${it.duration} (${(it.distanceMeters / 1000).round(1)} km)")- })- }- is TransitRoute.Step.TransitStep -> {- if(idx > 0 && route.steps[idx-1] is TransitRoute.Step.TransitStep) {- val prev = route.steps[idx-1] as TransitRoute.Step.TransitStep- if(prev.arrivalStation == it.departureStation) {- ListItem({- Text("Transfer")- })- }- }- Row(Modifier.height(IntrinsicSize.Min)) {- Surface(Modifier.fillMaxHeight().width(10.dp), RoundedCornerShape(12.dp), color = Color(it.lineColor.toColorInt())) {}- Column {- ListItem({- Text(it.departureStation)- })- ListItem({- Surface(- Modifier,- RoundedCornerShape(12.dp),- Color(it.lineColor.toColorInt())- ) {- Text(- it.lineName,- Modifier.padding(- horizontal = 12.dp,- vertical = 2.dp- )- )- }- }, supportingContent = {- Text(it.lineDirection)- }, trailingContent = {- Text(- it.departureTime.toLocalDateTime(- TimeZone.currentSystemDefault()- ).time.format(TIME_FORMAT)- )- })- ListItem({- Text(it.arrivalStation)- }, trailingContent = {- Text(- it.arrivalTime.toLocalDateTime(- TimeZone.currentSystemDefault()- ).time.format(TIME_FORMAT)- )- })- }- }- }- }- }- }- Card(shape = verticalShape(1, 2)) {- ListItem({- val origin = (selectedFeature as SpecificFeature.Route).to?.name ?: "Your location"- Text(origin)- }, trailingContent = {- Text(route.endTime().toLocalDateTime(TimeZone.currentSystemDefault()).time.format(TIME_FORMAT))- })- }- } else if(route is RouteService.Route) {- route.step.forEachIndexed { idx, it ->- Card(shape = verticalShape(idx, route.step.size)) {- ListItem({- Text(it.navInstruction.instructions)- }, leadingContent = {- it.navInstruction.maneuver.icon()?.let {- Icon(painterResource(it), null)- }- })- }- }- }+ }, colors = TopAppBarDefaults.topAppBarColors(Color.Transparent))+ }) { innerPadding ->+ Box(Modifier.padding(innerPadding).fillMaxSize()) {+ MaplibreMap(Modifier,+ BaseStyle.Json(json),+ camera,+ options = MapOptions(RenderOptions(), GestureOptions.Standard, OrnamentOptions.AllDisabled),+ onMapClick = { _, offset ->+ coroutineScope.launch {+ val projection = camera.projection+ val features = projection?.queryRenderedFeatures(offset, setOf("places_country", "places_region", "pois").flatMap {+ listOf("${it}_base", "${it}_hybrid")+ }.toSet()) ?: emptyList()+ println("FEATURES: $features")+ val listedFeatures = features.mapNotNull { parse(it) }+ println("LISTED FEATURES: $listedFeatures")++ listedFeatures.firstOrNull()?.let {+ selectedFeature = it+ scaffoldState.bottomSheetState.expand() } }+ ClickResult.Pass }+ ) {+ MyMapLayers(selectedFeature, route?.get(selectedRouteType)) }- else -> Unit- }- }- }, Modifier, scaffoldState, 170.dp) { paddingValues ->- Box(Modifier.padding(top = paddingValues.calculateTopPadding())) {- Scaffold { paddingValues ->- val coroutineScope = rememberCoroutineScope()- val style = rememberStyleState()- Box(Modifier.padding(paddingValues).fillMaxSize()) {-- MaplibreMap(Modifier,- BaseStyle.Json(patchStyleForHybrid(LocalContext.current.assets.open("style.json").source().readLines().joinToString("\n"), ensurePmtilesReady(LocalContext.current), "pmtiles://https://demo-bucket.protomaps.com/v4.pmtiles")),- 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?.get(selectedRouteType))++ // USER ICON+ key(camera.position) {+ Canvas(Modifier.fillMaxSize()) {+ UserIcon(userPosition, userBearing, camera) }+ } - key(camera.position) {- Canvas(Modifier.fillMaxSize()) {- if (userPosition != Position(0.0, 0.0) && camera.projection != null) {- val offset =- camera.projection!!.screenLocationFromPosition(userPosition)-- val centerOffset = Offset(offset.x.toPx(), offset.y.toPx())- val arcRadius = 20.dp.toPx() // The distance from center to the arc's stroke- val strokeWidth = 8.dp.toPx() // How thick the arc is-- drawCircle(- Color(0xFFFFFFFF),- center = centerOffset,- radius = 9.5.dp.toPx()- )- drawCircle(- Color(0xFF0E35F1),- center = centerOffset,- radius = 8.dp.toPx()- )--// Create a radial gradient that fades out- val fadingBrush = Brush.radialGradient(- 0f to Color(0xFF0E35F1), // Opaque blue at the very center- 0.8f to Color(0xFF0E35F1), // Stay opaque until the arc's edge- 1.0f to Color.Transparent, // Fade to nothing- center = centerOffset,- radius = arcRadius + strokeWidth // Gradient ends just past the stroke- )--- drawArc(- brush = fadingBrush,- startAngle = userBearing - 90f - 30f, // Start position (3 o'clock)- sweepAngle = 60f, // Length of the arc- useCenter = false, // Set to false for a curved line, true for a pie slice- topLeft = Offset(centerOffset.x - arcRadius, centerOffset.y - arcRadius),- size = Size(arcRadius * 2, arcRadius * 2),- style = Stroke(width = strokeWidth, cap = StrokeCap.Round)- )- }+ // ROUTE OVERLAY HEADERS+ 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)) } }+ } - 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))+ // DOWNLOAD DIALOG+ if (showDownloadDialog && activeZone != null) {+ androidx.compose.material3.AlertDialog(+ onDismissRequest = {+ showDownloadDialog = false+ dismissedZone = activeZone+ },+ title = { Text("Download Offline Map?") },+ text = { Text("You are viewing Zone $activeZone. Would you like to download the high-detail offline map (approx. 4.7GB)?") },+ confirmButton = {+ androidx.compose.material3.Button(onClick = {+ zoneManager.startDownload(activeZone)+ showDownloadDialog = false+ // We don't need to set dismissedZone here because getZoneStatus+ // will now return DOWNLOADING, preventing the effect from re-triggering+ }) {+ Text("Download") }- 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))+ },+ dismissButton = {+ androidx.compose.material3.TextButton(onClick = {+ showDownloadDialog = false+ dismissedZone = activeZone+ }) {+ Text("Cancel") } }- }+ ) } } } } } -fun createInvertedMask(countryFeature: Feature1): Feature1 {- // 1. World Rectangle (Clockwise)- val worldOuterRing = listOf(- Position(-180.0, 90.0), // Top Left- Position(180.0, 90.0), // Top Right- Position(180.0, -90.0), // Bottom Right- Position(-180.0, -90.0), // Bottom Left- Position(-180.0, 90.0) // Close- )+/**+ * Maps GPS coordinates to your 45x22.5 grid.+ */+fun calculateZoneId(lat: Double, lon: Double, zoom: Float): Int? {+ if (zoom < 7f) return null - // 2. Extract and Reverse the country rings (force them to be holes)- val holes = when (val geom = countryFeature.geometry) {- is Polygon -> listOf(geom.coordinates.first().reversed())- is MultiPolygon -> geom.coordinates.map { it.first().reversed() }- else -> emptyList()- }+ val lonIdx = ((lon + 180) / 45).toInt().coerceIn(0, 7)+ val latIdx = ((lat + 90) / 22.5).toInt().coerceIn(0, 7) - // 3. Create Polygon: [Outer, Hole1, Hole2...]- val donutGeometry = Polygon(listOf(worldOuterRing) + holes)- return Feature(geometry = donutGeometry, properties = countryFeature.properties)+ return (latIdx * 8) + lonIdx } -lateinit var outlineSource: GeoJsonSource-lateinit var routeSource: GeoJsonSource--@Composable-@MaplibreComposable-fun MyMapLayers(selectedFeature: SpecificFeature?, route: RouteService.RouteType?) {- val context = LocalContext.current- when (selectedFeature) {- is SpecificFeature.Admin0Label -> {- LaunchedEffect(selectedFeature) {- outlineSource.setData(GeoJsonData.Features(FeatureCollection(listOf(createInvertedMask(CountryMap.getAdmin0(context, selectedFeature.iso3166_1)!!)))))- }- FillLayer("global-mask", outlineSource,- //filter = const(true),- color = const(Color.Black.copy(alpha = 0.4f))- )- LineLayer("layer2", outlineSource,- //filter = const(true),- color = const(Color.Red)- )- }-- is SpecificFeature.Admin1Label -> {- LaunchedEffect(selectedFeature) {- outlineSource.setData(GeoJsonData.Features(FeatureCollection(listOf(createInvertedMask(CountryMap.getAdmin1(context, selectedFeature.iso3166_2)!!)))))- }- FillLayer("global-mask", outlineSource,- //filter = const(true),- color = const(Color.Black.copy(alpha = 0.4f))- )- LineLayer("layer2", outlineSource,- //filter = const(true),- color = const(Color.Red)- )- }-- is SpecificFeature.Route -> {- if(route != null) {- LaunchedEffect(route) {- if(route is RouteService.Route) {- val features: List<Feature1> = listOf<Feature1>(- //Feature1(LineString(route.polyline), JsonObject(emptyMap()))- ) + route.step.mapIndexed { idx, it ->- Feature1(- LineString(it.polyline),- JsonObject(mapOf("color" to JsonPrimitive("#1710F1")))- )- }- routeSource.setData(GeoJsonData.Features(FeatureCollection(features)))- } else if(route is TransitRoute) {- val features: List<Feature1> = route.steps.mapNotNull {- when(it) {- is TransitRoute.Step.WalkStep -> {- Feature1(- LineString(it.polyline),- JsonObject(mapOf("color" to JsonPrimitive("#1710F1")))- )- }- is TransitRoute.Step.TransitStep -> {- Feature1(- LineString(it.polyline),- JsonObject(mapOf("color" to JsonPrimitive(it.lineColor)))- )- }- }- }- routeSource.setData(GeoJsonData.Features(FeatureCollection(features)))- }- }- LineLayer("route", routeSource,- color = feature["color"].cast<StringValue>().convertToColor(), width = const(8.dp), cap = const(LineCap.Round)- )- }- }-- else -> Unit- }-}--fun patchStyleForHybrid(jsonString: String, localUrl: String, remoteUrl: String): String {+fun patchStyleForHybrid(+ jsonString: String,+ baseLocalUrl: String,+ hybridUrl: String+): String { val json = Json { ignoreUnknownKeys = true } val root = json.parseToJsonElement(jsonString).jsonObject - // 1. Update/Add the two sources- val oldSources = root["sources"]?.jsonObject ?: buildJsonObject {} val newSources = buildJsonObject {- // Keep any existing sources- //oldSources.forEach { (k, v) -> put(k, v) }-- // Define our specific pmtiles sources- putJsonObject("protomaps") {+ putJsonObject("protomaps_base") { put("type", "vector")- put("url", localUrl)+ put("url", baseLocalUrl) }- putJsonObject("protomapsOnline") {+ putJsonObject("protomaps_hybrid") { put("type", "vector")- put("url", remoteUrl)+ put("url", hybridUrl) } } - // 2. Duplicate layers with zoom boundaries val oldLayers = root["layers"]?.jsonArray ?: buildJsonArray {} val newLayers = buildJsonArray { oldLayers.forEach { layerElement ->@@ -623,33 +405,27 @@ fun patchStyleForHybrid(jsonString: String, localUrl: String, remoteUrl: String) if (type == "background") { add(layer) } else {- // Local Version: Zoom 0 to 7+ // Zoom 0-7: Base Local add(buildJsonObject { layer.forEach { (k, v) -> put(k, v) }- put("id", "${id}_local")- put("source", "protomaps")+ put("id", "${id}_base")+ put("source", "protomaps_base") put("maxzoom", 7) })-- // Online Version: Zoom 7 and up+ // Zoom 7+: Hybrid (Switches between Local and Remote) add(buildJsonObject { layer.forEach { (k, v) -> put(k, v) }- put("id", "${id}_online")- put("source", "protomapsOnline")+ put("id", "${id}_hybrid")+ put("source", "protomaps_hybrid") put("minzoom", 7) }) } } } - // 3. Reconstruct final style object- val finalStyle = buildJsonObject {- root.forEach { (k, v) ->- if (k != "sources" && k != "layers") put(k, v)- }+ return buildJsonObject {+ root.forEach { (k, v) -> if (k != "sources" && k != "layers") put(k, v) } put("sources", newSources) put("layers", newLayers)- }-- return finalStyle.toString()+ }.toString() }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/components/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/components/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/components/BottomSheetContent.ktnew file mode 100644index 0000000000..76839fdb88--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/components/BottomSheetContent.kt@@ -0,0 +1,184 @@+package com.vayunmathur.maps.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.IntrinsicSize+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Card+import androidx.compose.material3.Icon+import androidx.compose.material3.ListItem+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.PrimaryTabRow+import androidx.compose.material3.Surface+import androidx.compose.material3.Tab+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.unit.dp+import androidx.core.graphics.toColorInt+import com.vayunmathur.library.util.round+import com.vayunmathur.maps.RouteService+import com.vayunmathur.maps.TransitRoute+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.ui.RestaurantBottomSheet+import com.vayunmathur.maps.ui.verticalShape+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.format+import kotlinx.datetime.format.Padding+import kotlinx.datetime.toLocalDateTime++@Composable+fun BottomSheetContent(selectedFeature: SpecificFeature?, setSelectedFeature: (SpecificFeature?) -> Unit, route: Map<RouteService.TravelMode, RouteService.RouteType>?, selectedRouteType: RouteService.TravelMode, setSelectedRouteType: (RouteService.TravelMode) -> Unit) {+ when (selectedFeature) {+ is SpecificFeature.Admin0Label -> {+ Column {+ Text(selectedFeature.name, style = MaterialTheme.typography.titleLarge)+ Text(selectedFeature.wikipedia, style = MaterialTheme.typography.bodyMedium)+ }+ }+ is SpecificFeature.Admin1Label -> {+ Column {+ Text(selectedFeature.name, style = MaterialTheme.typography.titleLarge)+ Text(selectedFeature.wikipedia, style = MaterialTheme.typography.bodyMedium)+ }+ }+ is SpecificFeature.Restaurant -> {+ RestaurantBottomSheet(selectedFeature) {+ setSelectedFeature(SpecificFeature.Route(null, selectedFeature))+ }+ }+ is SpecificFeature.Route -> {+ if(route != null) {+ Column {+ PrimaryTabRow(route.entries.indexOfFirst { it.key == selectedRouteType }) {+ route.entries.forEach { it ->+ Tab(+ selectedRouteType == it.key,+ { setSelectedRouteType(it.key) }) {+ Text(+ it.key.name.lowercase()+ .replaceFirstChar { it.uppercase() })+ }+ }+ }+ val route = route[selectedRouteType]!!+ ListItem({ Text(route.duration.toString()) }, supportingContent = {+ Text("${(route.distanceMeters / 1000.0).round(2)} km")+ })+ Spacer(Modifier.height(8.dp))+ Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(2.dp)) {+ if(route is TransitRoute) {+ val TIME_FORMAT = LocalTime.Format {+ amPmHour(Padding.NONE)+ chars(":")+ minute()+ amPmMarker(" AM", " PM")+ }+ Card(shape = verticalShape(0, 2)) {+ ListItem({+ val origin = selectedFeature.from?.name ?: "Your location"+ Text(origin)+ }, trailingContent = {+ Text(route.startTime().toLocalDateTime(TimeZone.currentSystemDefault()).time.format(TIME_FORMAT))+ })+ }+ route.steps.forEachIndexed { idx, it ->+ Card() {+ when(it) {+ is TransitRoute.Step.WalkStep -> {+ ListItem({+ Text("Walk ${it.duration} (${(it.distanceMeters / 1000).round(1)} km)")+ })+ }+ is TransitRoute.Step.TransitStep -> {+ if(idx > 0 && route.steps[idx-1] is TransitRoute.Step.TransitStep) {+ val prev = route.steps[idx-1] as TransitRoute.Step.TransitStep+ if(prev.arrivalStation == it.departureStation) {+ ListItem({+ Text("Transfer")+ })+ }+ }+ Row(Modifier.height(IntrinsicSize.Min)) {+ Surface(Modifier.fillMaxHeight().width(10.dp), RoundedCornerShape(12.dp), color = Color(it.lineColor.toColorInt())) {}+ Column {+ ListItem({+ Text(it.departureStation)+ })+ ListItem({+ Surface(+ Modifier,+ RoundedCornerShape(12.dp),+ Color(it.lineColor.toColorInt())+ ) {+ Text(+ it.lineName,+ Modifier.padding(+ horizontal = 12.dp,+ vertical = 2.dp+ )+ )+ }+ }, supportingContent = {+ Text(it.lineDirection)+ }, trailingContent = {+ Text(+ it.departureTime.toLocalDateTime(+ TimeZone.currentSystemDefault()+ ).time.format(TIME_FORMAT)+ )+ })+ ListItem({+ Text(it.arrivalStation)+ }, trailingContent = {+ Text(+ it.arrivalTime.toLocalDateTime(+ TimeZone.currentSystemDefault()+ ).time.format(TIME_FORMAT)+ )+ })+ }+ }+ }+ }+ }+ }+ Card(shape = verticalShape(1, 2)) {+ ListItem({+ val origin = selectedFeature.to?.name ?: "Your location"+ Text(origin)+ }, trailingContent = {+ Text(route.endTime().toLocalDateTime(TimeZone.currentSystemDefault()).time.format(TIME_FORMAT))+ })+ }+ } else if(route is RouteService.Route) {+ route.step.forEachIndexed { idx, it ->+ Card(shape = verticalShape(idx, route.step.size)) {+ ListItem({+ Text(it.navInstruction.instructions)+ }, leadingContent = {+ it.navInstruction.maneuver.icon()?.let {+ Icon(painterResource(it), null)+ }+ })+ }+ }+ }+ }+ }+ }+ }+ else -> Unit+ }+}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/components/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/components/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/components/MyMapLayers.ktnew file mode 100644index 0000000000..e5283f141e--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/components/MyMapLayers.kt@@ -0,0 +1,155 @@+package com.vayunmathur.maps.ui.components++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import com.vayunmathur.maps.CountryMap+import com.vayunmathur.maps.RouteService+import com.vayunmathur.maps.TransitRoute+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.SpecificFeature+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import org.maplibre.compose.expressions.dsl.const+import org.maplibre.compose.expressions.dsl.convertToColor+import org.maplibre.compose.expressions.dsl.feature+import org.maplibre.compose.expressions.value.LineCap+import org.maplibre.compose.expressions.value.StringValue+import org.maplibre.compose.layers.FillLayer+import org.maplibre.compose.layers.LineLayer+import org.maplibre.compose.sources.*+import org.maplibre.compose.util.MaplibreComposable+import org.maplibre.spatialk.geojson.*++private lateinit var outlineSource: GeoJsonSource+private lateinit var routeSource: GeoJsonSource++@Composable+@MaplibreComposable+fun MyMapLayers(selectedFeature: SpecificFeature?, route: RouteService.RouteType?) {+ LaunchedEffect(Unit) {+ outlineSource = GeoJsonSource("selected-country-geojson", GeoJsonData.Features(+ Feature(Polygon(+ coordinates = listOf(+ listOf(+ Position(-180.0, -90.0),+ Position(180.0, -90.0),+ Position(180.0, 90.0),+ Position(-180.0, 90.0),+ Position(-180.0, -90.0) // Close the ring+ )+ )+ ), 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())++ }+ val context = LocalContext.current+ when (selectedFeature) {+ is SpecificFeature.Admin0Label -> {+ LaunchedEffect(selectedFeature) {+ outlineSource.setData(+ GeoJsonData.Features(+ FeatureCollection(+ listOf(+ createInvertedMask(+ CountryMap.getAdmin0(+ context,+ selectedFeature.iso3166_1+ )!!+ )+ )+ )+ ))+ }+ FillLayer("global-mask", outlineSource,+ //filter = const(true),+ color = const(Color.Black.copy(alpha = 0.4f))+ )+ LineLayer("layer2", outlineSource,+ //filter = const(true),+ color = const(Color.Red)+ )+ }++ is SpecificFeature.Admin1Label -> {+ LaunchedEffect(selectedFeature) {+ outlineSource.setData(GeoJsonData.Features(FeatureCollection(listOf(createInvertedMask(CountryMap.getAdmin1(context, selectedFeature.iso3166_2)!!)))))+ }+ FillLayer("global-mask", outlineSource,+ //filter = const(true),+ color = const(Color.Black.copy(alpha = 0.4f))+ )+ LineLayer("layer2", outlineSource,+ //filter = const(true),+ color = const(Color.Red)+ )+ }++ is SpecificFeature.Route -> {+ if(route != null) {+ LaunchedEffect(route) {+ if(route is RouteService.Route) {+ val features: List<Feature1> = listOf<Feature1>(+ //Feature1(LineString(route.polyline), JsonObject(emptyMap()))+ ) + route.step.mapIndexed { idx, it ->+ Feature1(+ LineString(it.polyline),+ JsonObject(mapOf("color" to JsonPrimitive("#1710F1")))+ )+ }+ routeSource.setData(GeoJsonData.Features(FeatureCollection(features)))+ } else if(route is TransitRoute) {+ val features: List<Feature1> = route.steps.mapNotNull {+ when(it) {+ is TransitRoute.Step.WalkStep -> {+ Feature1(+ LineString(it.polyline),+ JsonObject(mapOf("color" to JsonPrimitive("#1710F1")))+ )+ }+ is TransitRoute.Step.TransitStep -> {+ Feature1(+ LineString(it.polyline),+ JsonObject(mapOf("color" to JsonPrimitive(it.lineColor)))+ )+ }+ }+ }+ routeSource.setData(GeoJsonData.Features(FeatureCollection(features)))+ }+ }+ LineLayer("route", routeSource,+ color = feature["color"].cast<StringValue>().convertToColor(), width = const(8.dp), cap = const(+ LineCap.Round)+ )+ }+ }++ else -> Unit+ }+}++private fun createInvertedMask(countryFeature: Feature1): Feature1 {+ // 1. World Rectangle (Clockwise)+ val worldOuterRing = listOf(+ Position(-180.0, 90.0), // Top Left+ Position(180.0, 90.0), // Top Right+ Position(180.0, -90.0), // Bottom Right+ Position(-180.0, -90.0), // Bottom Left+ Position(-180.0, 90.0) // Close+ )++ // 2. Extract and Reverse the country rings (force them to be holes)+ val holes = when (val geom = countryFeature.geometry) {+ is Polygon -> listOf(geom.coordinates.first().reversed())+ is MultiPolygon -> geom.coordinates.map { it.first().reversed() }+ else -> emptyList()+ }++ // 3. Create Polygon: [Outer, Hole1, Hole2...]+ val donutGeometry = Polygon(listOf(worldOuterRing) + holes)+ return Feature(geometry = donutGeometry, properties = countryFeature.properties)+}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/components/RestaurantBottomSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/components/RestaurantBottomSheet.ktsimilarity index 97%rename from maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.ktrename to maps/src/main/java/com/vayunmathur/maps/ui/components/RestaurantBottomSheet.ktindex 41c99d6f26..860840ca0e 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantComponent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/components/RestaurantBottomSheet.kt@@ -16,7 +16,6 @@ import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults-import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable@@ -36,6 +35,7 @@ import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.core.net.toUri import com.vayunmathur.maps.R+import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.timeFormat import kotlinx.datetime.TimeZone import kotlinx.datetime.format@@ -53,7 +53,7 @@ fun RestaurantBottomSheet(feature: SpecificFeature.Restaurant, requestDirections val context = LocalContext.current Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(verticalAlignment = Alignment.CenterVertically) {- Text(feature.name ?: "", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))+ Text(feature.name, style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f)) Button({requestDirections()}) { Text("Directions") } } feature.openingHours?.let {
maps/src/main/java/com/vayunmathur/maps/ui/components/UserIcon.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/components/UserIcon.kt b/maps/src/main/java/com/vayunmathur/maps/ui/components/UserIcon.ktnew file mode 100644index 0000000000..1daa6c3fcf--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/components/UserIcon.kt@@ -0,0 +1,54 @@+package com.vayunmathur.maps.ui.components++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.StrokeCap+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.unit.dp+import org.maplibre.compose.camera.CameraState+import org.maplibre.spatialk.geojson.Position++fun DrawScope.UserIcon(userPosition: Position, userBearing: Float, camera: CameraState) {+ if (userPosition != Position(0.0, 0.0) && camera.projection != null) {+ val offset =+ camera.projection!!.screenLocationFromPosition(userPosition)++ val centerOffset = Offset(offset.x.toPx(), offset.y.toPx())+ val arcRadius = 20.dp.toPx() // The distance from center to the arc's stroke+ val strokeWidth = 8.dp.toPx() // How thick the arc is++ drawCircle(+ Color(0xFFFFFFFF),+ center = centerOffset,+ radius = 9.5.dp.toPx()+ )+ drawCircle(+ Color(0xFF0E35F1),+ center = centerOffset,+ radius = 8.dp.toPx()+ )++// Create a radial gradient that fades out+ val fadingBrush = Brush.radialGradient(+ 0f to Color(0xFF0E35F1), // Opaque blue at the very center+ 0.8f to Color(0xFF0E35F1), // Stay opaque until the arc's edge+ 1.0f to Color.Transparent, // Fade to nothing+ center = centerOffset,+ radius = arcRadius + strokeWidth // Gradient ends just past the stroke+ )+++ drawArc(+ brush = fadingBrush,+ startAngle = userBearing - 90f - 30f, // Start position (3 o'clock)+ sweepAngle = 60f, // Length of the arc+ useCenter = false, // Set to false for a curved line, true for a pie slice+ topLeft = Offset(centerOffset.x - arcRadius, centerOffset.y - arcRadius),+ size = Size(arcRadius * 2, arcRadius * 2),+ style = Stroke(width = strokeWidth, cap = StrokeCap.Round)+ )+ }+}\ No newline at end of file