maps: offline routing
- Commit
e8e2dbc2ea64d315eacc9cbf686d2ea20894bbef- Author
- Vayun Mathur <[email protected]>
- When
- 2026-03-11 00:22 UTC (9 months ago)
- Parents
9f2a468
Diff
library/src/main/java/com/vayunmathur/library/services/DownloadService.kt
diff --git a/library/src/main/java/com/vayunmathur/library/services/DownloadService.kt b/library/src/main/java/com/vayunmathur/library/services/DownloadService.ktindex ebcfd24e3a..6d13420aae 100644--- a/library/src/main/java/com/vayunmathur/library/services/DownloadService.kt+++ b/library/src/main/java/com/vayunmathur/library/services/DownloadService.kt@@ -60,6 +60,7 @@ class DownloadService : Service() { var lastTime = System.currentTimeMillis() try {+ if(ds.getBoolean("done_$fileName", false)) return@forEachIndexed downloadFileWithResume(url, destFile) { downloaded, total -> val currentTime = System.currentTimeMillis() val timeDiff = (currentTime - lastTime) / 1000.0
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex 7bef37a3f4..f47e46f702 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -116,6 +116,10 @@ class DataStoreUtils private constructor(context: Context) { } } + fun getBoolean(string: String, bool: Boolean): Boolean {+ return stateMap[booleanPreferencesKey(string)] as Boolean? ?: bool+ }+ companion object { @Volatile private var instance: DataStoreUtils? = null
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 64d08b75ce..e0e0c6f5a4 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -6,6 +6,13 @@ android { defaultConfig { applicationId = "com.vayunmathur.maps" }++ externalNativeBuild {+ cmake {+ path = file("src/main/cpp/CMakeLists.txt")+ version = "3.22.1"+ }+ } } dependencies {
maps/src/main/cpp/CMakeLists.txt
diff --git a/maps/src/main/cpp/CMakeLists.txt b/maps/src/main/cpp/CMakeLists.txtnew file mode 100644index 0000000000..100a8eb3da--- /dev/null+++ b/maps/src/main/cpp/CMakeLists.txt@@ -0,0 +1,7 @@+cmake_minimum_required(VERSION 3.10.2)+project("offlinerouter")++add_library(offlinerouter SHARED native-lib.cpp)++find_library(log-lib log)+target_link_libraries(offlinerouter ${log-lib})\ No newline at end of file
maps/src/main/cpp/native-lib.cpp
diff --git a/maps/src/main/cpp/native-lib.cpp b/maps/src/main/cpp/native-lib.cppnew file mode 100644index 0000000000..d037c32233--- /dev/null+++ b/maps/src/main/cpp/native-lib.cpp@@ -0,0 +1,180 @@+#include <jni.h>+#include <sys/mman.h>+#include <fcntl.h>+#include <unistd.h>+#include <vector>+#include <queue>+#include <string>+#include <cmath>+#include <algorithm>+#include <android/log.h>++#define TAG "OfflineRouterNative"+#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)++#pragma pack(push, 1)+struct NodePos { int32_t lat_e7, lon_e7; };+struct Edge { uint32_t source, target, dist_mm; uint8_t type; };+struct SpatialNode { uint64_t spatial_id; uint32_t local_id; };+#pragma pack(pop)++NodePos* g_nodes = nullptr;+uint64_t* g_edge_index = nullptr;+Edge* g_edges = nullptr;+SpatialNode* g_spatial = nullptr; // Added spatial mapping+size_t g_node_count = 0;++// Mapping function for Z-Order Curve+uint64_t latlng_to_spatial(double lat, double lon) {+ double x = (lon + 180.0) / 360.0;+ double y = (lat + 90.0) / 180.0;+ uint32_t ix = (uint32_t)(x * 4294967295.0);+ uint32_t iy = (uint32_t)(y * 4294967295.0);+ uint64_t res = 0;+ for (int i = 0; i < 32; i++) {+ res |= ((uint64_t)((ix >> i) & 1) << (2 * i));+ res |= ((uint64_t)((iy >> i) & 1) << (2 * i + 1));+ }+ return res;+}++// Binary search on the spatial index to find the nearest routable node+uint32_t find_nearest_node(double lat, double lon) {+ uint64_t target_spatial = latlng_to_spatial(lat, lon);++ // Find first element not less than target+ auto it = std::lower_bound(g_spatial, g_spatial + g_node_count, target_spatial,+ [](const SpatialNode& a, uint64_t val) {+ return a.spatial_id < val;+ });++ // Check neighbors to find the absolute closest spatial ID+ uint32_t best_id = 0;+ if (it == g_spatial + g_node_count) {+ best_id = (g_spatial + g_node_count - 1)->local_id;+ } else if (it == g_spatial) {+ best_id = it->local_id;+ } else {+ // Compare current 'it' and 'prev(it)' for closest match+ uint64_t diff1 = it->spatial_id - target_spatial;+ uint64_t diff2 = target_spatial - (it - 1)->spatial_id;+ best_id = (diff1 < diff2) ? it->local_id : (it - 1)->local_id;+ }+ return best_id;+}++uint32_t haversine_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_e7, int32_t lon2_e7) {+ double lat1 = (lat1_e7 / 1e7) * (M_PI / 180.0);+ double lon1 = (lon1_e7 / 1e7) * (M_PI / 180.0);+ double lat2 = (lat2_e7 / 1e7) * (M_PI / 180.0);+ double lon2 = (lon2_e7 / 1e7) * (M_PI / 180.0);+ double dlat = lat2 - lat1;+ double dlon = lon2 - lon1;+ double a = sin(dlat / 2) * sin(dlat / 2) + cos(lat1) * cos(lat2) * sin(dlon / 2) * sin(dlon / 2);+ return (uint32_t)(2 * atan2(sqrt(a), sqrt(1 - a)) * 6371000.0 * 1000.0);+}++void* map_file(const char* path, size_t& size) {+ int fd = open(path, O_RDONLY);+ if (fd < 0) return nullptr;+ size = lseek(fd, 0, SEEK_END);+ void* addr = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);+ close(fd);+ return addr;+}++extern "C" JNIEXPORT jboolean JNICALL+Java_com_vayunmathur_maps_OfflineRouter_init(JNIEnv* env, jobject thiz, jstring base_path) {+ const char* path = env->GetStringUTFChars(base_path, 0);+ size_t s1, s2, s3, s4;+ std::string base(path);+ g_nodes = (NodePos*)map_file((base + "/nodes_lookup.bin").c_str(), s1);+ g_edge_index = (uint64_t*)map_file((base + "/edge_index.bin").c_str(), s2);+ g_edges = (Edge*)map_file((base + "/edges.bin").c_str(), s3);+ g_spatial = (SpatialNode*)map_file((base + "/nodes_spatial.bin").c_str(), s4);++ g_node_count = s1 / sizeof(NodePos);+ env->ReleaseStringUTFChars(base_path, path);+ return g_nodes && g_edge_index && g_edges && g_spatial;+}++extern "C" JNIEXPORT jdoubleArray JNICALL+Java_com_vayunmathur_maps_OfflineRouter_findShortestRouteNative(JNIEnv* env, jobject thiz,+ jdouble sLat, jdouble sLon, jdouble eLat, jdouble eLon) {+ // 1. SNAPPING: Find actual start and end IDs from GPS+ uint32_t start_id = find_nearest_node(sLat, sLon);+ uint32_t end_id = find_nearest_node(eLat, eLon);++ LOGD("Snapped Start: %u (%.7f, %.7f) | Snapped End: %u (%.7f, %.7f)",+ start_id, g_nodes[start_id].lat_e7/1e7, g_nodes[start_id].lon_e7/1e7,+ end_id, g_nodes[end_id].lat_e7/1e7, g_nodes[end_id].lon_e7/1e7);++ // 2. A* SEARCH+ std::vector<uint32_t> g_score(g_node_count, 0xFFFFFFFF);+ std::vector<uint32_t> parent(g_node_count, 0xFFFFFFFF);+ using NodeDist = std::pair<uint32_t, uint32_t>;+ std::priority_queue<NodeDist, std::vector<NodeDist>, std::greater<NodeDist>> pq;++ g_score[start_id] = 0;+ uint32_t h_initial = haversine_mm(g_nodes[start_id].lat_e7, g_nodes[start_id].lon_e7,+ g_nodes[end_id].lat_e7, g_nodes[end_id].lon_e7);+ pq.push({h_initial, start_id});++ uint32_t nodes_visited = 0;+ uint32_t min_h = h_initial;++ while (!pq.empty()) {+ uint32_t u = pq.top().second;+ pq.pop();+ nodes_visited++;++ uint32_t current_h = haversine_mm(g_nodes[u].lat_e7, g_nodes[u].lon_e7,+ g_nodes[end_id].lat_e7, g_nodes[end_id].lon_e7);++ if (current_h < min_h) {+ min_h = current_h;+ LOGD("[Progress] Closer: %.7f, %.7f (%.2f m to goal)",+ g_nodes[u].lat_e7 / 1e7, g_nodes[u].lon_e7 / 1e7, current_h / 1000.0);+ }++ if (nodes_visited % 100 == 0) { // Increased log interval for performance+ LOGD("Visited: %u | MinDist: %.2f m", nodes_visited, min_h / 1000.0);+ }++ if (u == end_id) {+ LOGD("Path found! Nodes searched: %u", nodes_visited);+ break;+ }++ uint64_t start_off = g_edge_index[u];+ uint64_t end_off = g_edge_index[u + 1];++ for (uint64_t i = start_off; i < end_off; ++i) {+ Edge& e = g_edges[i];+ uint32_t v = e.target;+ if (g_score[u] + e.dist_mm < g_score[v]) {+ g_score[v] = g_score[u] + e.dist_mm;+ parent[v] = u;+ uint32_t h = haversine_mm(g_nodes[v].lat_e7, g_nodes[v].lon_e7,+ g_nodes[end_id].lat_e7, g_nodes[end_id].lon_e7);+ pq.push({g_score[v] + h, v});+ }+ }+ }++ // 3. RECONSTRUCTION+ std::vector<double> flat_coords;+ if (g_score[end_id] != 0xFFFFFFFF) {+ for (uint32_t curr = end_id; curr != 0xFFFFFFFF; curr = parent[curr]) {+ flat_coords.push_back(g_nodes[curr].lat_e7 / 1e7);+ flat_coords.push_back(g_nodes[curr].lon_e7 / 1e7);+ }+ std::reverse(flat_coords.begin(), flat_coords.end());+ } else {+ LOGD("Route not found between requested points.");+ }++ jdoubleArray result = env->NewDoubleArray(flat_coords.size());+ env->SetDoubleArrayRegion(result, 0, flat_coords.size(), flat_coords.data());+ return result;+}\ No newline at end of file
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 1fc6e825ed..ff61eac8ff 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -38,6 +38,7 @@ import com.vayunmathur.maps.ui.DownloadedMapsPage import com.vayunmathur.maps.ui.MapPage import com.vayunmathur.maps.ui.SearchPage import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking import kotlinx.serialization.Serializable import java.io.File @@ -62,6 +63,13 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() val ds = DataStoreUtils.getInstance(this) ensurePmtilesReady(this)+ println(OfflineRouter.checkFiles(this))+// runBlocking {+// File(getExternalFilesDir(null)!!, "edge_index.bin").delete()+// ds.setBoolean("dbSetupComplete", false)+// ds.setBoolean("done_edge_index.bin", false)+// }+// finish() setContent { DynamicTheme { InitialDownloadChecker(ds, listOf(
maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.ktindex 4172af2e1b..e6d766ab51 100644--- a/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/OfflineRouter.kt@@ -1,265 +1,84 @@ package com.vayunmathur.maps import android.content.Context+import android.util.Log+import com.vayunmathur.maps.data.SpecificFeature import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.maplibre.spatialk.geojson.Position import java.io.File-import java.io.RandomAccessFile-import java.nio.ByteOrder-import java.nio.MappedByteBuffer-import java.nio.channels.FileChannel-import java.util.PriorityQueue-import kotlin.math.atan2-import kotlin.math.cos-import kotlin.math.sin-import kotlin.math.sqrt+import kotlin.time.Duration.Companion.minutes object OfflineRouter {-- private var nodesLookupFile: LargeMappedFile? = null- private var nodesSpatialFile: LargeMappedFile? = null- private var edgesFile: LargeMappedFile? = null- private var edgeIndexFile: LargeMappedFile? = null-- // Helper class to bypass Java's 2GB MappedByteBuffer limit- private class LargeMappedFile(file: File, val recordSize: Int) {- private val channel = RandomAccessFile(file, "r").channel- val numRecords = file.length() / recordSize-- // Chunk size: Maximum 1GB, rounded down to the nearest multiple of recordSize- // This ensures a record is NEVER split across two different byte buffers- private val maxChunkSize = (1 shl 30) - ((1 shl 30) % recordSize)- private val buffers = mutableListOf<MappedByteBuffer>()-- init {- var offset = 0L- val fileSize = file.length()- while (offset < fileSize) {- val size = minOf(maxChunkSize.toLong(), fileSize - offset)- val buffer = channel.map(FileChannel.MapMode.READ_ONLY, offset, size)- buffer.order(ByteOrder.LITTLE_ENDIAN) // Must match C++ output- buffers.add(buffer)- offset += size- }- }-- fun getBufferAndOffset(recordIndex: Long): Pair<MappedByteBuffer, Int> {- val globalByteOffset = recordIndex * recordSize- val bufferIndex = (globalByteOffset / maxChunkSize).toInt()- val localOffset = (globalByteOffset % maxChunkSize).toInt()- return Pair(buffers[bufferIndex], localOffset)- }- }-- private class AStarNode(val localId: UInt, val fScore: Long) : Comparable<AStarNode> {- override fun compareTo(other: AStarNode): Int = this.fScore.compareTo(other.fScore)- }-- private data class EdgeData(val target: UInt, val distMm: Long, val type: UByte)-- @Synchronized- fun init(context: Context) {- if (nodesLookupFile != null) return // Already initialized-- val dir = context.getExternalFilesDir(null) ?: return- nodesLookupFile = LargeMappedFile(File(dir, "nodes_lookup.bin"), 8)- nodesSpatialFile = LargeMappedFile(File(dir, "nodes_spatial.bin"), 12)- edgesFile = LargeMappedFile(File(dir, "edges.bin"), 13)- edgeIndexFile = LargeMappedFile(File(dir, "edge_index.bin"), 8) // NEW 8-byte edge bounds index+ init {+ System.loadLibrary("offlinerouter") } - /**- * Calculates the shortest path between start and end.- * Suspend function ensures the UI thread is not blocked during heavy disk I/O.- */- suspend fun findShortestRoute(context: Context, start: Position, end: Position): List<Position> = withContext(Dispatchers.IO) {- init(context)+ private const val TAG = "OfflineRouter" - val startId = findClosestNode(start.latitude, start.longitude) ?: return@withContext emptyList()- val endId = findClosestNode(end.latitude, end.longitude) ?: return@withContext emptyList()+ fun checkFiles(context: Context) {+ val dir = context.getExternalFilesDir(null)!!+ val files = listOf(+ "nodes_lookup.bin" to 8, // 8 bytes per node+ "nodes_spatial.bin" to 12, // 12 bytes per node+ "edge_index.bin" to 8, // 8 bytes per node (+1 sentinel)+ "edges.bin" to 13 // 13 bytes per edge+ ) - if (startId == endId) return@withContext listOf(start)+ Log.d(TAG, "--- Binary Stack Health Check ---") - val openSet = PriorityQueue<AStarNode>()- val cameFrom = HashMap<UInt, UInt>()- val gScore = HashMap<UInt, Long>() // Exact distance from start to node+ files.forEach { (name, structSize) ->+ val file = File(dir, name)+ if (file.exists()) {+ val size = file.length()+ val count = if (name == "edge_index.bin") (size / structSize) - 1 else size / structSize - gScore[startId] = 0L- openSet.add(AStarNode(startId, heuristic(startId, end)))+ Log.d(TAG, "File: $name")+ Log.d(TAG, " Size: ${size} bytes")+ Log.d(TAG, " Implied Count: $count items") - while (openSet.isNotEmpty()) {- val current = openSet.poll() ?: break-- if (current.localId == endId) {- return@withContext reconstructPath(cameFrom, current.localId, startId)- }-- val currentGScore = gScore[current.localId] ?: continue-- // If we already found a shorter path to this node since queueing, skip it- if (current.fScore - heuristic(current.localId, end) > currentGScore) continue-- val edges = getEdges(current.localId)- for (edge in edges) {- val tentativeGScore = currentGScore + edge.distMm- val neighborGScore = gScore.getOrDefault(edge.target, Long.MAX_VALUE)-- if (tentativeGScore < neighborGScore) {- cameFrom[edge.target] = current.localId- gScore[edge.target] = tentativeGScore-- val fScore = tentativeGScore + heuristic(edge.target, end)- openSet.add(AStarNode(edge.target, fScore))+ // Integrity check: file size should be a multiple of the struct size+ if (name != "edge_index.bin" && size % structSize != 0L) {+ Log.e(TAG, " WARNING: File size is not a multiple of $structSize. File may be corrupt.") }+ } else {+ Log.e(TAG, "File: $name - NOT FOUND at ${file.absolutePath}") } }-- return@withContext emptyList() // No path found } - private fun reconstructPath(cameFrom: HashMap<UInt, UInt>, current: UInt, start: UInt): List<Position> {- val path = mutableListOf<Position>()- var curr = current- while (cameFrom.containsKey(curr)) {- getLookupNode(curr)?.let { path.add(it) }- curr = cameFrom[curr]!!- }- getLookupNode(start)?.let { path.add(it) }- path.reverse()- return path- }-- private fun getEdges(sourceId: UInt): List<EdgeData> {- val indexFile = edgeIndexFile ?: return emptyList()- val edgeFile = edgesFile ?: return emptyList()-- // Verify we aren't querying out of bounds (should never happen for valid IDs)- if (sourceId.toLong() >= indexFile.numRecords - 1) return emptyList()-- // 1. O(1) Lookup: Find the exact start index of edges for this node- val (bufStart, offStart) = indexFile.getBufferAndOffset(sourceId.toLong())- val startIndex = bufStart.getLong(offStart).toULong()+ private external fun init(basePath: String): Boolean+ private external fun findShortestRouteNative(sLat: Double, sLon: Double, eLat: Double, eLon: Double): DoubleArray - // 2. O(1) Lookup: Find where the NEXT node's edges start to get our upper bound- val (bufEnd, offEnd) = indexFile.getBufferAndOffset(sourceId.toLong() + 1)- val endIndex = bufEnd.getLong(offEnd).toULong()+ private var isInitialized = false - // If startIndex == endIndex, this node has 0 outgoing edges- if (startIndex == endIndex) return emptyList()-- // 3. Extract the edges directly without any binary search looping!- val result = mutableListOf<EdgeData>()- for (i in startIndex until endIndex) {- val (buffer, offset) = edgeFile.getBufferAndOffset(i.toLong())-- // Skip the first 4 bytes (sourceId) since we already know it- val target = buffer.getInt(offset + 4).toUInt()- val distMm = buffer.getInt(offset + 8).toUInt().toLong()- val type = buffer.get(offset + 12).toUByte()-- result.add(EdgeData(target, distMm, type))- }-- return result+ suspend fun getRoute(context: Context, route: SpecificFeature.Route, userPosition: Position): RouteService.Route = withContext(Dispatchers.Default) {+ val start = route.waypoints.first()?.position ?: userPosition+ val end = route.waypoints.last()?.position ?: userPosition+ return@withContext getRoute(context, start, end) } - private fun findClosestNode(lat: Double, lon: Double): UInt? {- val file = nodesSpatialFile ?: return null- val targetSpatial = latLngToSpatial(lat, lon)-- var low = 0L- var high = file.numRecords - 1- var bestIndex = -1L-- // Binary search for the closest Z-Order curve spatial ID- while (low <= high) {- val mid = (low + high) ushr 1- val (buffer, offset) = file.getBufferAndOffset(mid)- val midSpatial = buffer.getLong(offset).toULong()-- if (midSpatial < targetSpatial) {- low = mid + 1- bestIndex = mid- } else if (midSpatial > targetSpatial) {- high = mid - 1- bestIndex = mid- } else {- bestIndex = mid- break- }+ suspend fun getRoute(context: Context, start: Position, end: Position): RouteService.Route = withContext(Dispatchers.Default) {+ if (!isInitialized) {+ isInitialized = init(context.getExternalFilesDir(null)!!.absolutePath) } - if (bestIndex == -1L) return null-- // Z-Order curves can have local discontinuities. We scan a 200-node window- // around the insertion point to find the physical absolute closest node.- val searchWindow = 200L- val startIndex = maxOf(0L, bestIndex - searchWindow)- val endIndex = minOf(file.numRecords - 1, bestIndex + searchWindow)+ // Get raw doubles: [lat0, lon0, lat1, lon1...]+ val rawCoords = findShortestRouteNative(start.latitude, start.longitude, end.latitude, end.longitude) - var closestId: UInt? = null- var minDistance = Double.MAX_VALUE-- for (i in startIndex..endIndex) {- val (buf, off) = file.getBufferAndOffset(i)- val localId = buf.getInt(off + 8).toUInt()-- val pos = getLookupNode(localId)- if (pos != null) {- val dist = haversine(lat, lon, pos.latitude, pos.longitude)- if (dist < minDistance) {- minDistance = dist- closestId = localId- }- }+ // Chunk the array by 2 to create Position objects+ val positions = mutableListOf<Position>()+ for (i in rawCoords.indices step 2) {+ positions.add(Position(rawCoords[i], rawCoords[i + 1])) } - return closestId- }-- private fun getLookupNode(localId: UInt): Position? {- val file = nodesLookupFile ?: return null- if (localId.toLong() >= file.numRecords) return null-- val (buffer, offset) = file.getBufferAndOffset(localId.toLong())- val lat = buffer.getInt(offset) / 10000000.0- val lon = buffer.getInt(offset + 4) / 10000000.0-- // Safety check to ensure we don't route to "Null Island" for missing data- if (lat == 0.0 && lon == 0.0) return null-- return Position(lon, lat)- }-- private fun heuristic(localId: UInt, endPos: Position): Long {- val pos = getLookupNode(localId) ?: return Long.MAX_VALUE- val distMeters = haversine(pos.latitude, pos.longitude, endPos.latitude, endPos.longitude)- return (distMeters * 1000.0).toLong() // Return in millimeters to match Edge distance units- }-- // Identical port of the C++ Z-Order implementation using native Kotlin Unsigned types- private fun latLngToSpatial(lat: Double, lon: Double): ULong {- val x = (lon + 180.0) / 360.0- val y = (lat + 90.0) / 180.0- val ix = (x * 4294967295.0).toUInt().toULong()- val iy = (y * 4294967295.0).toUInt().toULong()- var res = 0UL- for (i in 0 until 32) {- res = res or (((ix shr i) and 1UL) shl (2 * i))- res = res or (((iy shr i) and 1UL) shl (2 * i + 1))- }- return res- }-- private fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {- val r = 6371000.0 // Earth radius in meters- val dLat = Math.toRadians(lat2 - lat1)- val dLon = Math.toRadians(lon2 - lon1)- val a = sin(dLat / 2) * sin(dLat / 2) +- cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *- sin(dLon / 2) * sin(dLon / 2)- val c = 2 * atan2(sqrt(a), sqrt(1 - a))- return r * c+ RouteService.Route(+ duration = 5.minutes, // You could calculate this in C++ and return as part of the array+ distanceMeters = 100.0,+ polyline = positions,+ step = listOf(RouteService.Step(+ 100.0, 5.minutes, positions, RouteService.API.NavInstruction(), RouteService.TravelMode.WALK)+ )+ ) } }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/SelectedFeatureViewModel.ktindex c92c84fc43..022063fac1 100644--- a/maps/src/main/java/com/vayunmathur/maps/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/SelectedFeatureViewModel.kt@@ -42,6 +42,8 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli RouteService.TravelMode.entries.associateWith { if(it == RouteService.TravelMode.TRANSIT) { TransitRoute.computeRoute(routeFeature, userPosition.value)+ } else if(it == RouteService.TravelMode.WALK) {+ OfflineRouter.getRoute(application.applicationContext, routeFeature, userPosition.value) } else { RouteService.computeRoute(routeFeature, userPosition.value, it) }