Maps Android KTX

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 file.

dependencies {
    // KTX for the Maps SDK for Android
    implementation 'com.google.maps.android:maps-ktx:3.2.1'

    // (Optional) KTX for the Maps SDK for Android Utility Library
    implementation 'com.google.maps.android:maps-utils-ktx:3.2.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.launchWhenCreated {
  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.launchWhenCreated {
  googleMap.cameraMoveEvents().collect {
    print("Received camera move event")
  }
}

You can see a full list of supported features by reading the reference documentation.