maps: intercept geo:/google.navigation:/Google-Maps-URL intents like Vela
- Commit
c453a06b00a76e9c929c18961486539681e68320- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-17 22:24 UTC (3 months ago)
- Parents
973e9d5
Register ACTION_VIEW intent-filters for geo:, google.navigation: and http(s) Google Maps links (www.google.com/maps, google.com/maps, maps.google.com, maps.app.goo.gl, goo.gl/maps); MainActivity is now singleTop and parses the intent in onCreate + onNewIntent. MapLinkParser (pure Kotlin, mirrors Vela + extended) yields a MapLink: - geo:lat,lng[?q=&z=], geo:0,0?q=lat,lng(label), geo:0,0?q=<address> - google.navigation:q=<lat,lng|address>[&mode=d/w/b/l] - /maps place/search/@coord/?q= and /dir/ directions (+travelmode) Routing: a location opens the place + bottom pane (geocoding the query via GoogleSearchDataSource when needed); a navigation link resolves the destination, routes from the user's location via OfflineRouter and starts turn-by-turn through NavigationSessionManager. Malformed/empty links are ignored (never crash).
Diff
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex 33defc60bd..b9ad24cdfd 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -78,12 +78,48 @@ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:name=".MainActivity" android:exported="true"+ android:launchMode="singleTop" android:theme="@style/Theme.General"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>++ <!-- geo: links from other apps (assistant, contacts, browsers) → this+ app can be the system maps handler. geo:lat,lng[?q=&z=],+ geo:0,0?q=lat,lng(label), geo:0,0?q=<address>. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="geo" />+ </intent-filter>++ <!-- Turn-by-turn requests: google.navigation:q=<lat,lng|address>[&mode=d/w/b/l]+ → start guidance to the destination. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="google.navigation" />+ </intent-filter>++ <!-- Google-Maps web links → "open in maps" offers this app too. Covers+ place/search/@coord/?q= links and /dir/ directions, plus the short+ maps.app.goo.gl / goo.gl/maps share links. -->+ <intent-filter android:autoVerify="false">+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="https" />+ <data android:scheme="http" />+ <data android:host="www.google.com" android:pathPrefix="/maps" />+ <data android:host="google.com" android:pathPrefix="/maps" />+ <data android:host="maps.google.com" />+ <data android:host="maps.app.goo.gl" />+ <data android:host="goo.gl" android:pathPrefix="/maps" />+ </intent-filter> </activity> <!-- Live navigation foreground service. Owns the ongoing
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 c343ce59be..bb3de31c6e 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -1,14 +1,18 @@ package com.vayunmathur.maps import android.Manifest+import android.content.Intent import android.os.Build import android.os.Bundle+import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.library.downloadservice.InitialDownloadChecker import com.vayunmathur.library.ui.DynamicTheme@@ -18,6 +22,10 @@ import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.maps.data.MapLink+import com.vayunmathur.maps.data.MapLinkParser+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.google.GoogleSearchDataSource import com.vayunmathur.maps.ui.MapPage import com.vayunmathur.maps.ui.SavedPlacesPage import com.vayunmathur.maps.ui.SearchPage@@ -26,18 +34,33 @@ import com.vayunmathur.maps.data.MapPreferences import com.vayunmathur.maps.data.ThemeMode import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.MapsSearchViewModel+import com.vayunmathur.maps.util.NavigationService+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.OfflineRouter+import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.GooglePoiMapViewModel import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.Serializable import org.maplibre.android.log.Logger+import org.maplibre.spatialk.geojson.Position import java.io.File class MainActivity : ComponentActivity() { + // Same instances the Compose tree gets via viewModel() (both resolve to this+ // Activity's ViewModelStore), so an external geo:/maps/navigation intent handled+ // here shows up in the map UI: selecting a place opens its bottom pane, and a+ // navigation link drives the shared NavigationSessionManager.+ private val selectedVm: SelectedFeatureViewModel by viewModels()+ private val searchVm: MapsSearchViewModel by viewModels()+ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // FIRST_PARTY: data.vayunmathur.com tiles + amenities + api.vayunmathur.com -> ISRG+GTS@@ -51,14 +74,9 @@ class MainActivity : ComponentActivity() { File(filesDir, "world_z0-6.pmtiles").delete() val ds = DataStoreUtils.getInstance(this) Logger.setVerbosity(Logger.INFO)-//-// runBlocking {-// ds.setBoolean("dbSetupComplete", false)-// ds.setBoolean("done_metadata.bin", false)-// ds.setBoolean("done_road_names.bin", false)-// File(getExternalFilesDir(null), "metadata.bin").delete()-// File(getExternalFilesDir(null), "road_names.bin").delete()-// }++ // Deep link that launched us cold (geo:/google.navigation:/maps URL).+ handleIntent(intent) setContent { val themeMode by ds.stringFlow(MapPreferences.KEY_THEME_MODE)@@ -95,6 +113,147 @@ class MainActivity : ComponentActivity() { } } }++ // Warm start: the app was already running when another app fired a geo:/maps/+ // navigation intent at us. singleTop (see AndroidManifest) routes it here.+ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ setIntent(intent)+ handleIntent(intent)+ }++ /**+ * Turn an external ACTION_VIEW `geo:` / `google.navigation:` / Google-Maps web+ * link into either an opened place (select + bottom pane) or a started+ * navigation session. Malformed/empty links are ignored (never crash).+ */+ private fun handleIntent(intent: Intent?) {+ if (intent?.action != Intent.ACTION_VIEW) return+ val data = intent.dataString ?: return+ val link = MapLinkParser.parse(data)+ if (link == null) {+ Log.i(TAG, "ACTION_VIEW ignored (unparseable): $data")+ return+ }+ Log.i(TAG, "ACTION_VIEW routed data=$data -> $link")+ if (link.navigate) navigateTo(link) else openPlace(link)+ }++ /** Select a place from the link and open its bottom pane (Vela place-card). */+ private fun openPlace(link: MapLink) {+ val lat = link.lat+ val lng = link.lng+ val query = link.query+ when {+ // A point with a name/label → drop it straight in (no network).+ lat != null && lng != null && !query.isNullOrBlank() -> {+ selectedVm.selectAndFocus(genericPlace(query, lat, lng), link.zoom)+ }+ // A bare point → reverse-geocode for a name; fall back to a plain pin.+ lat != null && lng != null -> {+ searchVm.reverseGeocode(lat, lng) { place ->+ selectedVm.selectAndFocus(+ place ?: genericPlace(getString(R.string.dropped_pin), lat, lng),+ link.zoom,+ )+ }+ }+ // A query only → run the Google search and auto-select the first hit+ // (same path as the contact-address shortcut).+ !query.isNullOrBlank() -> {+ val near = biasPosition()+ searchVm.searchAndSelectFirst(query, near.latitude, near.longitude) { first ->+ if (first != null) selectedVm.selectAndFocus(searchVm.toFeature(first), link.zoom)+ else Log.i(TAG, "openPlace: no search result for \"$query\"")+ }+ }+ }+ }++ /** Resolve the link's destination, route from the user's location, and start guidance. */+ private fun navigateTo(link: MapLink) {+ lifecycleScope.launch {+ val mode = link.mode ?: RouteService.TravelMode.DRIVE+ // Destination position: an explicit coord, else geocode the query.+ val destPos: Position?+ val destName: String+ if (link.lat != null && link.lng != null) {+ destPos = Position(link.lng, link.lat)+ destName = link.query ?: getString(R.string.dropped_pin)+ } else if (!link.query.isNullOrBlank()) {+ val near = biasPosition()+ val hit = GoogleSearchDataSource.search(link.query, near.latitude, near.longitude).firstOrNull()+ destPos = hit?.let { Position(it.lng, it.lat) }+ destName = hit?.name ?: link.query+ } else {+ destPos = null+ destName = getString(R.string.dropped_pin)+ }+ if (destPos == null) {+ Log.i(TAG, "navigateTo: could not resolve destination for $link")+ return@launch+ }++ val destFeature = SpecificFeature.GenericPlace(+ name = destName, phone = null, website = null, openingHours = null, position = destPos,+ )+ // A null first waypoint means "from current location".+ val route = SpecificFeature.Route(listOf(null, destFeature))++ // Wait briefly for a real GPS fix so the first leg starts from the user.+ val origin = awaitUserPosition()+ if (origin == null) {+ // No fix yet: fall back to opening the destination place + pane so the+ // user can hit Start Navigation manually (which waits for location).+ Log.i(TAG, "navigateTo: no location fix; opening destination place instead")+ selectedVm.selectAndFocus(destFeature)+ return@launch+ }++ val computed = try {+ OfflineRouter.getRouteMulti(applicationContext, route, origin, mode)+ } catch (e: Exception) {+ Log.w(TAG, "navigateTo: routing failed", e); null+ }+ if (computed == null) {+ Log.i(TAG, "navigateTo: no route ($mode) to $destName; opening place instead")+ selectedVm.selectAndFocus(destFeature)+ return@launch+ }++ startForegroundService(Intent(applicationContext, NavigationService::class.java))+ NavigationSessionManager.init(applicationContext)+ NavigationSessionManager.start(+ route = computed,+ mode = mode,+ destination = destPos,+ destinationLabel = destName,+ )+ Log.i(TAG, "navigateTo: started $mode navigation to $destName")+ }+ }++ /** First valid GPS fix within [timeoutMs], or null. (0,0) means "no fix yet". */+ private suspend fun awaitUserPosition(timeoutMs: Long = 8_000): Position? =+ withTimeoutOrNull(timeoutMs) {+ selectedVm.userPosition.first { it.latitude != 0.0 || it.longitude != 0.0 }+ }++ /** Search bias: the user's live position when known, else the map's default centre. */+ private fun biasPosition(): Position {+ val p = selectedVm.userPosition.value+ return if (p.latitude != 0.0 || p.longitude != 0.0) p else Position(-118.243683, 34.052235)+ }++ private fun genericPlace(name: String, lat: Double, lng: Double) =+ SpecificFeature.GenericPlace(+ name = name, phone = null, website = null, openingHours = null,+ position = Position(lng, lat),+ )++ companion object {+ private const val TAG = "MapsIntent"+ } } @Serializable
maps/src/main/java/com/vayunmathur/maps/data/MapLinkParser.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/MapLinkParser.kt b/maps/src/main/java/com/vayunmathur/maps/data/MapLinkParser.ktnew file mode 100644index 0000000000..dc9f9bf190--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/MapLinkParser.kt@@ -0,0 +1,168 @@+package com.vayunmathur.maps.data++import com.vayunmathur.maps.util.RouteService+import java.net.URLDecoder++/**+ * A target extracted from an external `geo:` / `google.navigation:` URI or a+ * Google-Maps web link, so this app can be the system maps handler on a+ * de-Googled phone (mirrors Vela's MapLinkParser, extended for turn-by-turn).+ *+ * [zoom] is the caller's requested camera zoom (`geo:...?z=17`, `/@lat,lng,15z`)+ * when it carried one. [navigate] is true for `google.navigation:` and Google+ * `/maps/dir/` links, which should START guidance rather than just open a place;+ * [mode] is the requested travel mode when the link specified one.+ */+data class MapLink(+ val query: String? = null,+ val lat: Double? = null,+ val lng: Double? = null,+ val zoom: Double? = null,+ val navigate: Boolean = false,+ val mode: RouteService.TravelMode? = null,+) {+ val hasTarget: Boolean get() = !query.isNullOrBlank() || (lat != null && lng != null)+}++/**+ * Parses the links other apps hand to a maps app:+ * - `geo:38.5,-121.7` → a point+ * - `geo:0,0?q=Coffee` → a search+ * - `geo:38.5,-121.7?q=Pier 39` → a named place near a point+ * - `geo:0,0?q=38.5,-121.7(Label)` → a labelled point+ * - `google.navigation:q=38.5,-121.7&mode=d` → navigate (drive) to a point+ * - `google.navigation:q=Pier 39&mode=w` → navigate (walk) to a search+ * - `https://www.google.com/maps/place/Foo/@38.5,-121.7,15z` → a place / point+ * - `https://www.google.com/maps/search/coffee` / `?q=...` → a search+ * - `https://www.google.com/maps/dir/?...&destination=...` → navigate+ *+ * Pure Kotlin (no `android.net.Uri`) so it's unit-testable and never throws:+ * a malformed/unknown link returns null and the caller does nothing.+ */+object MapLinkParser {+ private val COORD = Regex("""(-?\d{1,3}\.\d+),\s*(-?\d{1,3}\.\d+)""")+ private val AT = Regex("""@(-?\d{1,3}\.\d+),(-?\d{1,3}\.\d+)""")++ fun parse(raw: String): MapLink? {+ val link = runCatching {+ when {+ raw.startsWith("geo:", ignoreCase = true) -> parseGeo(raw)+ raw.startsWith("google.navigation:", ignoreCase = true) -> parseNavigation(raw)+ "/maps" in raw || "maps.google" in raw ||+ "maps.app.goo.gl" in raw || "goo.gl/maps" in raw -> parseMaps(raw)+ else -> null+ }+ }.getOrNull()+ return link?.takeIf { it.hasTarget }+ }++ private fun parseGeo(raw: String): MapLink {+ val body = raw.substring(4) // after "geo:"+ val coordPart = body.substringBefore("?")+ var lat = COORD.find(coordPart)?.groupValues?.get(1)?.toDoubleOrNull()+ var lng = COORD.find(coordPart)?.groupValues?.get(2)?.toDoubleOrNull()+ if (lat == 0.0 && lng == 0.0) { lat = null; lng = null } // 0,0 = "no point, see ?q"+ // RFC-style zoom: geo:lat,lng?z=17 (1..21). Honoured for the camera; junk ignored.+ val zoom = queryParam(raw, "z")?.toDoubleOrNull()?.takeIf { it in 1.0..21.0 }++ val q = queryParam(raw, "q")?.let { decode(it) }+ if (!q.isNullOrBlank()) {+ // ?q can be "lat,lng(Label)", a bare "lat,lng", or an address/name.+ val label = Regex("""\(([^)]+)\)""").find(q)?.groupValues?.get(1)+ val qc = COORD.find(q)+ if (qc != null && lat == null) {+ return MapLink(query = label, lat = qc.groupValues[1].toDoubleOrNull(), lng = qc.groupValues[2].toDoubleOrNull(), zoom = zoom)+ }+ val text = label ?: q.takeUnless { COORD.matches(it.trim()) }+ return MapLink(query = text, lat = lat, lng = lng, zoom = zoom)+ }+ return MapLink(lat = lat, lng = lng, zoom = zoom)+ }++ /** `google.navigation:q=<lat,lng | address>[&mode=d/w/b/l]` → start guidance.+ * NB the params follow the scheme colon directly (no `?`), unlike geo:. */+ private fun parseNavigation(raw: String): MapLink {+ val body = raw.substringAfter("google.navigation:", "")+ val mode = travelModeFromLetter(paramIn(body, "mode"))+ val q = (paramIn(body, "q") ?: paramIn(body, "ll"))?.let { decode(it) }+ ?: return MapLink(navigate = true)+ COORD.matchEntire(q.trim())?.let {+ return MapLink(lat = it.groupValues[1].toDoubleOrNull(), lng = it.groupValues[2].toDoubleOrNull(), navigate = true, mode = mode)+ }+ return MapLink(query = q, navigate = true, mode = mode)+ }++ private fun parseMaps(raw: String): MapLink {+ val lat = AT.find(raw)?.groupValues?.get(1)?.toDoubleOrNull()+ val lng = AT.find(raw)?.groupValues?.get(2)?.toDoubleOrNull()+ // Google web links carry zoom after the @coords: /@38.5,-121.7,15z.+ val zoom = Regex("""@-?\d{1,3}\.\d+,-?\d{1,3}\.\d+,(\d+(?:\.\d+)?)z""")+ .find(raw)?.groupValues?.get(1)?.toDoubleOrNull()?.takeIf { it in 1.0..21.0 }++ // Directions link → navigate. Destination comes from the api=1 `destination=`+ // / classic `daddr=` param, else the last path segment after `/dir/`.+ if ("/dir/" in raw || "/dir?" in raw || raw.endsWith("/dir")) {+ val mode = travelModeFromWord(queryParam(raw, "travelmode") ?: queryParam(raw, "dirflg"))+ val destRaw = queryParam(raw, "destination") ?: queryParam(raw, "daddr")+ ?: dirDestinationSegment(raw)+ val dest = destRaw?.let { decode(it.replace('+', ' ')) }?.takeIf { it.isNotBlank() }+ if (dest != null) {+ COORD.matchEntire(dest.trim())?.let {+ return MapLink(lat = it.groupValues[1].toDoubleOrNull(), lng = it.groupValues[2].toDoubleOrNull(), navigate = true, mode = mode)+ }+ return MapLink(query = dest, navigate = true, mode = mode)+ }+ // No parseable destination but coords in the URL: navigate to those.+ if (lat != null && lng != null) return MapLink(lat = lat, lng = lng, navigate = true, mode = mode)+ return MapLink(navigate = true, mode = mode)+ }++ val place = Regex("""/place/([^/@?]+)""").find(raw)?.groupValues?.get(1)+ val search = Regex("""/search/([^/@?]+)""").find(raw)?.groupValues?.get(1)+ val q = queryParam(raw, "q") ?: queryParam(raw, "query")+ val query = (place ?: search ?: q)?.let { decode(it.replace('+', ' ')) }?.takeIf { it.isNotBlank() }+ // A query that's really coordinates → treat as a point.+ query?.trim()?.let { COORD.matchEntire(it) }?.let {+ return MapLink(lat = it.groupValues[1].toDoubleOrNull(), lng = it.groupValues[2].toDoubleOrNull(), zoom = zoom)+ }+ return MapLink(query = query, lat = lat, lng = lng, zoom = zoom)+ }++ /** Last meaningful segment after `/dir/` (skipping empties, `@camera` and `data=`). */+ private fun dirDestinationSegment(raw: String): String? {+ val after = raw.substringAfter("/dir/", "").substringBefore('?')+ if (after.isBlank()) return null+ return after.split('/')+ .filter { it.isNotBlank() && !it.startsWith("@") && !it.startsWith("data=") }+ .lastOrNull()+ }++ private fun travelModeFromLetter(letter: String?): RouteService.TravelMode? = when (letter?.lowercase()) {+ "d", "l" -> RouteService.TravelMode.DRIVE // l = two-wheeler; closest is drive+ "w" -> RouteService.TravelMode.WALK+ "b" -> RouteService.TravelMode.BICYCLE+ else -> null+ }++ private fun travelModeFromWord(word: String?): RouteService.TravelMode? = when (word?.lowercase()) {+ "driving", "d" -> RouteService.TravelMode.DRIVE+ "walking", "w" -> RouteService.TravelMode.WALK+ "bicycling", "b" -> RouteService.TravelMode.BICYCLE+ "transit", "r" -> RouteService.TravelMode.TRANSIT+ else -> null+ }++ private fun queryParam(raw: String, key: String): String? =+ paramIn(raw.substringAfter('?', ""), key)++ /** Find [key] in a raw `k=v&k=v` param string (no leading `?`). */+ private fun paramIn(query: String, key: String): String? {+ if (query.isEmpty()) return null+ return query.split('&').firstNotNullOfOrNull { p ->+ val (k, v) = p.split('=', limit = 2).let { it[0] to it.getOrElse(1) { "" } }+ if (k.equals(key, ignoreCase = true) && v.isNotEmpty()) v else null+ }+ }++ private fun decode(s: String): String = runCatching { URLDecoder.decode(s, "UTF-8") }.getOrDefault(s)+}
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 92cf893e29..8b2477651d 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -16,6 +16,9 @@ <!-- BottomSheet: Current location label. Noun. --> <string name="your_location">Your location</string>+ <!-- Place-pane title for a bare coordinate opened from a geo:/maps deep link+ that has no name and no reverse-geocode match. Noun. -->+ <string name="dropped_pin">Dropped pin</string> <!-- BottomSheet: Error when routing fails --> <string name="no_route_found">No route found</string> <!-- BottomSheet: Loading state while route is calculated -->