Modern Apps git

← Modern-Apps.git

maps: download nodes and edges along with pmtiles when zooming into an undownloaded tile

Commit
4f0904ab6efde92b637054b8b7ebb4aa4f10c98a
Author
Vayun Mathur <[email protected]>
When
2026-04-11 22:32 UTC (7 months ago)
Parents
3b248bd

Diff

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 6b379cae9f..347315879b 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -62,8 +62,6 @@ class MainActivity : ComponentActivity() {                 InitialDownloadChecker(ds, listOf(                     Triple("https://data.vayunmathur.com/amenities.db", "amenities.db", "Downloading Amenity Database..."),                     Triple("https://data.vayunmathur.com/metadata.bin", "metadata.bin", "Downloading Navigation Tiling Metadata..."),-                    Triple("https://data.vayunmathur.com/nodes_zone_35.bin", "nodes_zone_35.bin", "Downloading Routing Nodes..."),-                    Triple("https://data.vayunmathur.com/edges_zone_35.bin", "edges_zone_35.bin", "Downloading Routing Graph..."),                     Triple("https://data.vayunmathur.com/road_names.bin", "road_names.bin", "Downloading Road Data...")                 )) {                     val db = remember { buildAmenityDatabase(this@MainActivity) }
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.ktindex 7b0b997356..967f40ad99 100644--- a/maps/src/main/java/com/vayunmathur/maps/ZoneDownloadManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ZoneDownloadManager.kt@@ -24,7 +24,8 @@ class ZoneDownloadManager(private val context: Context) {      */     fun getDownloadingZonesFlow(): Flow<Map<Int, Float>> = flow {         while (true) {-            val progressMap = mutableMapOf<Int, Float>()+            val progressSumMap = mutableMapOf<Int, Float>()+            val countMap = mutableMapOf<Int, Int>()              // Query for any task that isn't finished or failed             val query = DownloadManager.Query().setFilterByStatus(@@ -44,13 +45,18 @@ class ZoneDownloadManager(private val context: Context) {                         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+                        progressSumMap[zoneId] = progressSumMap.getOrDefault(zoneId, 0f) + progress+                        countMap[zoneId] = countMap.getOrDefault(zoneId, 0) + 1                     }                 }             }             cursor.close() -            emit(progressMap)+            val finalProgressMap = progressSumMap.mapValues { (zoneId, sum) ->+                sum / (countMap[zoneId] ?: 1).toFloat()+            }++            emit(finalProgressMap)             delay(1000) // Poll faster (1s) for progress updates         }     }@@ -73,10 +79,17 @@ class ZoneDownloadManager(private val context: Context) {         }         cursor.close() -        // 2. Remove the file from disk-        val file = File(context.getExternalFilesDir(null), "zone_$zoneId.pmtiles")-        if (file.exists()) {-            file.delete()+        // 2. Remove the files from disk+        val files = listOf(+            "zone_$zoneId.pmtiles",+            "nodes_zone_$zoneId.bin",+            "edges_zone_$zoneId.bin"+        )+        files.forEach { fileName ->+            val file = File(context.getExternalFilesDir(null), fileName)+            if (file.exists()) {+                file.delete()+            }         }     } @@ -101,65 +114,50 @@ class ZoneDownloadManager(private val context: Context) {     }      fun getZoneStatus(zoneId: Int): ZoneStatus {-        val file = File(context.getExternalFilesDir(null), "zone_$zoneId.pmtiles")+        val pmtilesFile = File(context.getExternalFilesDir(null), "zone_$zoneId.pmtiles")+        val nodesFile = File(context.getExternalFilesDir(null), "nodes_zone_$zoneId.bin")+        val edgesFile = File(context.getExternalFilesDir(null), "edges_zone_$zoneId.bin")          val query = DownloadManager.Query()         val cursor = downloadManager.query(query)-        var foundStatus: ZoneStatus? = null+        var isDownloading = false          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+                if (systemStatus == DownloadManager.STATUS_RUNNING ||+                    systemStatus == DownloadManager.STATUS_PAUSED ||+                    systemStatus == DownloadManager.STATUS_PENDING) {+                    isDownloading = true                 }-                break             }         }         cursor.close() -        if (foundStatus != null) return foundStatus-        return if (file.exists()) ZoneStatus.FINISHED else ZoneStatus.NOT_STARTED-    }+        if (isDownloading) return ZoneStatus.DOWNLOADING -    fun startDownload(zoneId: Int) {-        val originalZoneId = getOriginalZoneIdFromMorton(zoneId)-        val url = "https://data.vayunmathur.com/zone_$originalZoneId.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)+        val allFilesExist = pmtilesFile.exists() && nodesFile.exists() && edgesFile.exists()+        return if (allFilesExist) ZoneStatus.FINISHED else ZoneStatus.NOT_STARTED     } -    private fun getOriginalZoneIdFromMorton(mortonZoneId: Int): Int {-        var lonIdx = 0-        var latIdx = 0--        // mortonZoneId is a 6-bit number (0-63)-        // Interleaving: Bit 5=Y2, Bit 4=X2, Bit 3=Y1, Bit 2=X1, Bit 1=Y0, Bit 0=X0--        // De-interleave Longitude (X) bits: bits 0, 2, 4-        if ((mortonZoneId and (1 shl 0)) != 0) lonIdx = lonIdx or (1 shl 0)-        if ((mortonZoneId and (1 shl 2)) != 0) lonIdx = lonIdx or (1 shl 1)-        if ((mortonZoneId and (1 shl 4)) != 0) lonIdx = lonIdx or (1 shl 2)--        // De-interleave Latitude (Y) bits: bits 1, 3, 5-        if ((mortonZoneId and (1 shl 1)) != 0) latIdx = latIdx or (1 shl 0)-        if ((mortonZoneId and (1 shl 3)) != 0) latIdx = latIdx or (1 shl 1)-        if ((mortonZoneId and (1 shl 5)) != 0) latIdx = latIdx or (1 shl 2)--        // Combine into row-major format (Lat * 8 + Lon)-        return (latIdx * 8) + lonIdx+    fun startDownload(zoneId: Int) {+        deleteZone(zoneId)+        val files = listOf(+            "zone_$zoneId.pmtiles" to "https://data.vayunmathur.com/zone_$zoneId.pmtiles",+            "nodes_zone_$zoneId.bin" to "https://data.vayunmathur.com/nodes_zone_$zoneId.bin",+            "edges_zone_$zoneId.bin" to "https://data.vayunmathur.com/edges_zone_$zoneId.bin"+        )++        files.forEach { (fileName, url) ->+            val request = DownloadManager.Request(url.toUri())+                .setTitle("Map Zone $zoneId")+                .setDescription("Downloading high-detail offline map data")+                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)+                .setDestinationInExternalFilesDir(context, null, fileName)+                .setAllowedOverMetered(true)++            downloadManager.enqueue(request)+        }     } }\ 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 c72f2f0644..421a7a1b45 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -113,18 +113,14 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     }      val hybridUrl = remember(activeZone) {-        val remoteUrl = "pmtiles://https://demo-bucket.protomaps.com/v4.pmtiles"--        if (activeZone == null) return@remember remoteUrl+        if (activeZone == null) return@remember ""          val localFile = File(context.getExternalFilesDir(null), "zone_$activeZone.pmtiles")-        val x = if (zoneManager.getZoneStatus(activeZone) == ZoneDownloadManager.ZoneStatus.FINISHED) {+        if (zoneManager.getZoneStatus(activeZone) == ZoneDownloadManager.ZoneStatus.FINISHED) {             "pmtiles://file://${localFile.absolutePath}"         } else {-            remoteUrl+            ""         }-        println("URL: $x")-        x     }      // Inside MapPage@@ -356,7 +352,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                 Text("Download")                             }                         }, 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)?") },+                        text = { Text("You are viewing Zone $activeZone. Would you like to download the high-detail offline map (approx. 4.7GB) to see more than just the overview?") },                         dismissButton = {                             TextButton({                                 showDownloadDialog = false@@ -376,7 +372,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,  * Maps GPS coordinates to your 45x22.5 grid.  */ fun calculateZoneId(lat: Double, lon: Double, zoom: Float): Int? {-    if(zoom < 6f) return null+    if(zoom < 7f) return null     // 1. Normalize coordinates to [0, 1] range     val normX = (lon + 180.0) / 360.0     val normY = (lat + 90.0) / 180.0@@ -432,19 +428,19 @@ fun patchStyleForHybrid(             if (type == "background") {                 add(layer)             } else {-                // Zoom 0-6: Base Local+                // Zoom 0-7: Base Local                 add(buildJsonObject {                     layer.forEach { (k, v) -> put(k, v) }                     put("id", "${id}_base")                     put("source", "protomaps_base")-                    put("maxzoom", 6)+                    put("maxzoom", 7)                 })-                // Zoom 6+: Hybrid (Switches between Local and Remote)+                // Zoom 7+: Hybrid (Local Only)                 add(buildJsonObject {                     layer.forEach { (k, v) -> put(k, v) }                     put("id", "${id}_hybrid")                     put("source", "protomaps_hybrid")-                    put("minzoom", 6)+                    put("minzoom", 7)                 })             }         }