Maps Android Kotlin extensions (KTX) are a collection of Kotlin extensions for the Maps SDK for Android and the Maps SDK for Android Utility Library. These extensions provide Kotlin language features that enable you to write concise and idiomatic Kotlin when developing for the Maps SDK for Android. Maps KTX is open-sourced and available on GitHub along with examples.
Installation
To install KTX for the Maps SDK for Android, and optionally for the Maps SDK for
Android Utility Library, add the following dependencies to your build.gradle.kts
file.
dependencies { // KTX for the Maps SDK for Android library implementation("com.google.maps.android:maps-ktx:5.1.1") }
Example Usages
With the KTX library, you can take advantage of several Kotlin language features such as extension functions, named parameters and default arguments, destructuring declarations, and coroutines.
Retrieving a GoogleMap using coroutines
Accessing a GoogleMap
can be retrieved
using coroutines.
lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) { val mapFragment: SupportMapFragment? = supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment val googleMap: GoogleMap? = mapFragment?.awaitMap() } }
Adding a marker
Adding a marker can be done using the DSL-style method addMarker()
.
val sydney = LatLng(-33.852, 151.211) val marker = googleMap.addMarker { position(sydney) title("Marker in Sydney") }
Collecting camera events
Events, such as camera moves, can be collected via Kotlin Flow.
lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) { googleMap.cameraMoveEvents().collect { print("Received camera move event") } } }
You can see a full list of supported features by reading the reference documentation.
Try the sample application
The GitHub repository for this library also contains a demo application that shows how you can use the Maps KTX library in your own app.
To try the demo application, follow these steps:
- From GitHub, clone the or download the ZIP file.
- In Android Studio, choose File -> Open and navigate to the directory and open the folder that you just cloned or downloaded.
- Add an API key to the demo app.
- Get a Maps SDK for Android key.
- In the root directory, create a file called
secrets.properties
. This file should NOT be under version control to protect your API key. - Add this single line to
secrets.properties
whereMAPS_API_KEY="YOUR_API_KEY"
YOUR_API_KEY
is the actual API key you obtained in the first step. You can look at thesecrets.defaults.properties
as an example. - Under the run configuration, select the module app-ktx.
- Select Run 'app-ktx'.
What's next
You may also be interested in other Kotlin extension libraries for Google Maps Platform: