I thought I would chip in with the Kotlin code.
I created a helper function that takes latitude
, longitude
and context
params to fire off the intent.
fun openGoogleMap(latitude: Double, longitude: Double, context: Context) { ... }
Inside the openGoogleMap()
helper function create an intent passing in the action, data to act upon (lat/long) and package name for the Google Map application.
fun openGoogleMap(latitude: Double, longitude: Double, context: Context) {
// you need action, data and package name
val uri = Uri.parse("geo:$latitude,$longitude?z=15")
//create an intent
val mapIntent = Intent()
//add action & data
mapIntent.action = Intent.ACTION_VIEW
mapIntent.data = uri
//package name for google maps app
mapIntent.setPackage("com.google.android.apps.maps")
try {
context.startActivity(mapIntent)
} catch (e: ActivityNotFoundException) {
//if map app isn't resolved/installed catch error
e.printStackTrace()
}
}
The docs say that
To verify that an app is available to receive the intent, call
resolveActivity() on your Intent object. If the result is non-null,
there is at least one app that can handle the intent and it's safe to
call startActivity().
But I found that using resolveActivity()
has issues when used with this code especially when you are outside the Activity's code.
mapIntent.resolveActivity(packageManager)?.let {
...
}
To get around this I used try-catch block to catch ActivityNotFoundException with startActivity().
mapIntent.setPackage("com.google.android.apps.maps")
try {
context.startActivity(mapIntent)
} catch (e: ActivityNotFoundException) {
//if map app isn't resolved/installed catch error
e.printStackTrace()
}
I tested the util function and it does work and is launching the GoogleMaps with Kotlin code.