Maps Compose Library Tutorial for Android: Getting Began

Google Maps is a contemporary toolkit that gives detailed details about geographical areas. Immediately, it has greater than a billion customers per day.

Nonetheless, it will get difficult if you need to use the previous library, Maps SDK for Android, with Jetpack Compose. You could write complicated and infrequently giant View interoperability code blocks to mix Jetpack Compose with the usual map UI element – MapView. This opposes one in all Jetpack Compose’s major targets of being easy and exact. To unravel this, Google created a brand new and easier approach of dealing with Google Maps in Jetpack Compose initiatives.

In February 2022, Google launched the Maps Compose library. It’s an open-source set of composable capabilities that simplify Google Maps implementation. Moreover that, the library comprises particular information sorts associated to Maps SDK for Android suited to Jetpack Compose.

On this tutorial, you’ll construct the GeoMarker app. The app means that you can use Maps Compose options like markers, circles and information home windows. Moreover, you’ll additionally have the ability to mark factors in your UI and have the ability to draw a polygon from chosen factors.

Through the course of, you’ll be taught:

  • Organising Google Maps in compose.
  • Requesting location permissions.
  • Including markers, information home windows and circles in your map.
  • Including customized map styling.
  • Drawing polygons in your map.
  • Testing some map options.

Getting Began

Obtain the starter challenge by clicking Obtain Supplies on the prime or backside of the tutorial.

Open Android Studio Chipmunk or later and import the starter challenge. Construct and run the challenge. You’ll see the next screens:

App first run screen

The app exhibits an empty display screen with a ‘Mark Space’ floating motion button on the backside. You’ll show your map and different map parts on this display screen. You’ll additionally add the geo-marking performance.

Setting Up

To begin engaged on maps in compose, you could full the next steps:

  1. Organising the dependencies:
      implementation ''
      implementation ''
      implementation ''

    The primary is the Maps Compose library, and the opposite two are the Play Providers maps SDK and placement SDKs. Be aware that these dependencies exist already within the starter challenge, so there’s no must re-add them.

  3. Secondly, you want a Google Maps API key for you to have the ability to use any of Google Maps APIs. You could find directions on how you can get your key right here. Upon getting your key, proceed so as to add it to your file as follows:

Now that you’ve every thing set, time to get your fingers soiled with maps in compose. You’ll begin by requesting location permissions on your app.

Requesting Location Permissions

Your app wants location permissions for you to have the ability to present maps. Head over to presentation/screens/MapScreenContent.kt. Substitute //TODO Add Permissions with:

// 1
val scope = rememberCoroutineScope()
// 2
val context = LocalContext.present
// 3
var showMap by rememberSaveable {
// 4
    context = context,
    permission = Manifest.permission.ACCESS_FINE_LOCATION,
    permissionRationale = stringResource(id = R.string.permission_location_rationale),
    snackbarHostState = snackbarHostState) { permissionAction ->
  // 5
  when (permissionAction) {
    is PermissionAction.PermissionDenied -> {
      showMap = false
    is PermissionAction.PermissionGranted -> {
      showMap = true
      scope.launch {
        snackbarHostState.showSnackbar("Location permission granted!")

To resolve errors, change your imports on the prime with:

import android.Manifest
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import kotlinx.coroutines.launch

Right here’s what the code above does:

  1. You create a CoroutineScope variable you’ll use to point out your Snackbar.
  2. It is a variable to get the context of your present composable.
  3. You’ve gotten a Boolean variable showMap that represents whether or not the app has crucial permissions.
  4. Right here, you name PermissionDialog, a customized composable that handles all of the permissions logic.
  5. The PermissionDialog has a callback that returns which permission choice the person has chosen. It could actually both be PermissionGranted or PermissionDenied. On every of this, you replace the showMap variable. When the person grants the permission, you present a Snackbar with a “Location permission granted!” message and begin the placement updates.

With this, you’re prepared to point out areas on a map, and that’s the following step.

Displaying a Place in a Map

Navigate to presentation/composables/MapView.kt. You’ll see two TODOs that you just’ll work on in a second.

However earlier than that, change your imports with the next:

import android.content material.Context
import androidx.compose.basis.structure.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

Begin by changing // TODO add Digital camera Place State with:

val cameraPositionState = rememberCameraPositionState {
  place = CameraPosition.fromLatLngZoom(location, 16f)

Within the code above, you create a CameraPositionState occasion, which holds the configurations on your map. On this case, you set your map’s location and zoom degree.

Second, change // TODO Add Google Map with:

    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState

GoogleMap is a container for a MapView, to which you move each values, modifier and cameraPositionState. And that’s all it is advisable to present a single location on a map in compose :]

Final, it is advisable to name your customized MapView composable in your MapScreenContent.kt. You move within the context and placement as parameters. For an instance, you’ll use a set location in Singapore. Return to presentation/screens/MapScreenContent.kt and under PermissionDialog add:

val currentLocation = LatLng(1.35, 103.87)
if (showMap) {
  MapView(context, currentLocation)

Add the next imports to your import statements to resolve the errors.


Right here, you added the conditional to examine whether or not your map must be displayed. As soon as the situation is met, you name MapView passing within the context and present location.

Construct and run the app:

Singapore location on map

The app now exhibits the placement in Singapore on the map. Within the subsequent part, you’ll add a marker to this location.

Including a Marker on the Map

Inside presentation/composables/MapView.kt, add a pair of curly braces to GoogleMap composable and add the next within the block:

    state = MarkerState(place = location),

Add any lacking imports by urgent Possibility-Return on a Mac or Alt-Enter on a Home windows PC. Your ultimate consequence will likely be:

    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState
) {
      state = MarkerState(place = location),

You add a marker in a map by including baby composables to GoogleMap as contents. A Marker requires a MarkerState occasion that observes marker state resembling its place and data window.

Cross the Singapore location to MarkerState after which construct and run the app.

Singapore marker

You may see the pink marker for Singapore on the heart of your map.

Usually, you’ll want to point out info when a person faucets a marker. For that, you’ll have so as to add InfoWindow to your map, which you’ll be taught subsequent.

Exhibiting Map Info Home windows

Head again to presentation/composables/MapView.kt and add this code under the cameraPositionState variable:

val infoWindowState = rememberMarkerState(place = location)

You’ve gotten now created a state variable for the marker properties and handed the placement to this marker.

Subsequent, under your Marker composable, add:

    state = infoWindowState,
    title = "My location",
    snippet = "Location customized information window",
    content material = {
      CustomInfoWindow(title = it.title, description = it.snippet)

Within the code above, you create your info window utilizing MarkerInfoWindow composable. You may customise your info window to your liking. You move the state, title, snippet and content material as parameters. Contained in the content material lambda, you name your customized composable together with your info window customized view.

Construct and run the app. Faucet the Singapore marker, and you need to see:

Singapore marker information window

The knowledge window shows on prime of the marker with texts from the title and snippet you handed as parameters.

Drawing Circles on Your Map

Thus far, you’ve seen how you can add markers and information home windows to your map. On this part, you’ll add one other form, a Circle.

In MapView.kt, add the next under MarkerInfoWindow within the GoogleMap composable:

    heart = location,
    fillColor = MaterialTheme.colorScheme.secondaryContainer,
    strokeColor = MaterialTheme.colorScheme.secondaryContainer,
    radius = 300.00

Resolve the MaterialTheme lacking imports by urgent Possibility-Return on a Mac or Alt-Enter on a PC.

Circle is one more map baby composable and has a number of parameters. For this tutorial, you solely must assign values to:

  • heart – the LatLng that represents the middle of this circle.
  • fillColor – fill shade of the circle.
  • strokeColor – shade of the outer circle or stroke.
  • radius – circle radius.

Construct and run the app.

Singapore map with circle

Now you can see a blue circle on the heart of your map. Its heart is the Singapore location that you just handed.

Thus far, you’ve drawn a number of shapes in your map. Within the subsequent part, you’ll discover ways to customise your map’s look by including a customized JSON map fashion.

Customizing the Look of Your Map

There are two map styling choices out there with maps:

  1. Cloud-based styling: This lets you create and edit map types with out requiring any adjustments in your app. You make all of the adjustments within the cloud console, that are mirrored in your apps after you have a map ID.
  2. JSON primarily based styling: Right here, you create a map fashion on the outdated fashion wizard . When you full the customization, you’ll be able to obtain the JSON file and add it to your map.

On this tutorial, you’ll be utilizing JSON styling. You’ll create your customized fashion so as to add to the map within the subsequent part.

Making a Customized JSON Map Styling

Open your most popular browser and head to the outdated fashion wizard. You need to see:

JSON map styling wizard

On the left, you’ve got customization choices resembling altering the density of the options and altering the theme of your map.

Begin by deciding on the Silver theme as proven under:

Wizard with silver-theme styling

On the best aspect, you’ll be able to see the map shade adjustments to replicate the chosen theme. Subsequent, click on MORE OPTIONS as proven above.

Styling wizard with more customization options

This exhibits an inventory of options you’ll be able to customise and visualize on the map. For this tutorial, you’ll customise the Highway characteristic.

Comply with these steps:

  • Click on the Highway characteristic, which is able to open up the component sort part on the best.
  • The weather sort part has an inventory of components you’ll be able to customise, which on this case are labels and geometry.
  • Click on the Geometry choice and alter the colour as per your choice. You may see the colour is instantly mirrored on the map.

Styling wizard advanced customization

That’s all for now. You may add as many customization choices as you want. Click on FINISH, and also you’ll see the Export Fashion dialog as proven:

Styling wizard export style

Click on COPY JSON choice. This copies the JSON fashion in your clipboard. You’re now a couple of steps away from making use of the customized fashion to your compose map.

Navigate again to Android Studio. Proper-click the res listing, select NewAndroid Useful resource Listing and choose uncooked. Within the new uncooked listing, create a file named map_style.json and paste the copied fashion right here.

Now, you’ve got the fashion prepared to be used. Subsequent, it is advisable to apply it to your map.

Making use of Customized Fashion to Your Map

Head over to presentation/composables/MapView.kt. Beneath your infoWindowState variable add:

val mapProperties by keep in mind {
          mapStyleOptions = MapStyleOptions.loadRawResourceStyle(context, R.uncooked.map_style)

Add any lacking imports by urgent Possibility-Return on a Mac or Alt-Enter on a PC. As seen above, you create a brand new state variable of sort MapProperties. This variable holds properties you’ll be able to change on the map. You move the customized fashion to the mapStyleOptions, which masses the fashion from the uncooked listing.

Subsequent, add this variable mapProperties as properties parameter to your GoogleMap. Your ultimate consequence must be:

    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState,
    properties = mapProperties
) {
  // Youngster Composables

Construct and run the app.

Map with custom JSON style

You may see your map now applies the fashion out of your JSON file.

Requesting Location Updates

Be aware: This part is non-compulsory. You may skip forward to Marking Polygon Positions if you wish to begin including your geo marking performance. Nonetheless, in case you’d like to know how you can do location updates, you’re in the best place! The performance is already within the starter challenge.

A typical characteristic of maps on gadgets is the flexibility for them to replace in actual time. To do this right here, You’ll use a callbackFlow to request for location updates. Inside utils bundle you’ll discover LocationUtils.kt file. The placement callbackFlow is as follows:

enjoyable FusedLocationProviderClient.locationFlow() = callbackFlow {
  val callback = object : LocationCallback() {
    override enjoyable onLocationResult(consequence: LocationResult) {
      strive {
      } catch (e: Exception) {
        Log.e("Error", e.message.toString())
  requestLocationUpdates(createLocationRequest(), callback, Looper.getMainLooper())
      .addOnFailureListener { e ->

  awaitClose {

Right here, you wrap your LocationCallback in a callbackFlow. Within the callbackFlow, callback is known as each time you’ve got location updates from requestLocationUpdates. And at last, you clear up assets when your callback is eliminated inside awaitClose.

Open up MainActivity.kt, and take a look at fetchLocationUpdates() to see the way it fetches location updates:

personal enjoyable fetchLocationUpdates() {
  lifecycleScope.launch {
    lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
      fusedLocationClient.locationFlow().gather {
        it?.let { location ->
          geoMarkerViewModel.setCurrentLatLng(LatLng(location.latitude, location.longitude))

This makes use of repeatOnLifecycle() to gather safely out of your Circulation within the UI. You additionally move the placement to your viewmodel to share the newest worth together with your composable.

Within the subsequent part, you’ll see how to attract polygons in your map and end the geo marking a part of the app.

Marking Polygon Positions

There are two choices out there to create your geo marker:

  • Drawing polylines: You utilize the placement replace characteristic to attract polylines as a person walks in a sure space. You draw polylines after a person updates their location at set intervals.
  • Draw polygons: You draw polygons from an inventory of LatLng coordinates. For this tutorial, you’ll be utilizing this selection.

Head over to presentation/screens/GeoMarkerScreen.kt and also you’ll see:

Geo Marker screen TODOs

On this file, you’ve got a GeoMarkerScreen composable that has a number of map state variables outlined. It has a Scaffold inside the place you’ve got your GoogleMap composable. You’ve gotten three TODOs you’ll handle in a second.

Construct and run the app. Faucet Mark Space.

Geo Marker screen

You may see the map and a button on the backside of the map. You’ll be including performance for including geo factors by clicking any three factors on the map.

To start with, change // TODO Add click on listener with:

if (!drawPolygon) {
  showSavePoint = true
  clickedLocation = it

Right here, you do a conditional examine to examine whether or not the polygon is already drawn. When the situation isn’t glad, you replace the showSavePoint, which is a Boolean that determines whether or not to point out the UI to avoid wasting the clicked level. Clicking a map additionally returns a LatLng of the clicked level. You assign this worth to the clickedLocation variable.

Subsequent, change // TODO Save Level UI with:

if (showSavePoint) {
  SaveGeoPoint(latLng = clickedLocation) {
    showSavePoint = it.hideSavePointUi
} else {
  if (areaPoints.isEmpty()) {
    Textual content(
        modifier = Modifier
        shade = Colour.Blue,
        textual content = "Click on any level on the map to mark it.",
        textAlign = TextAlign.Heart,
        fontWeight = FontWeight.Daring

Add any lacking imports by urgent Possibility-Return on a Mac or Alt-Enter on a PC. You add one other conditional examine.

When showSavePoint is true, you present the SaveGeoPoint composable. SaveGeoPoint is a customized composable with UI for saving the clicked level. You move the clickedLocation from the map click on listener. When the situation evaluates to false, you present a textual content with directions on how you can mark factors on the map.

Construct and run the app. Navigate to the Geo Marker Display as soon as extra. You’ll see:

Geo Marker screen with instructions

Faucet any level on the map.

Geo Marker screen with save location UI

You may see the UI to avoid wasting the purpose in your map. It shows the LatLng and the Save Level motion which saves your level.

You’ll discover if you save three factors that the Full button on the backside turns into lively. Faucet Full. Nothing occurs on the map; it solely exhibits a reset button. Like me, you have been anticipating to see a polygon. Don’t fear. You’ll repair this habits in a second.

Substitute // TODO Add Polygon with:

// 1
if (drawPolygon && areaPoints.isNotEmpty()) {
  // 2
  areaPoints.forEach {
    Marker(state = MarkerState(place = it))
  // 3
      factors = areaPoints,
      fillColor = Colour.Blue,
      strokeColor = Colour.Blue
// 4
if (showSavePoint) {
  Marker(state = MarkerState(place = clickedLocation))

Add any lacking imports by urgent Possibility-Return on a Mac or Alt-Enter on a PC.

Right here’s what the code above does:

  1. It is a conditional examine to examine whether or not the polygon is drawn. You additionally examine if the areaPoints has values since you want an inventory of LatLng to attract a polygon.
  2. Right here, for every merchandise within the areaPoints listing, you add a marker in your map.
  3. You utilize Polygon composable, to attract your polygon. You move within the factors to attract and the colours on your polygon.
  4. It is a marker for every level you click on on the map.

Construct and run the app, then faucet the marker space button and add three markers. Lastly, faucet the entire button.

Geo Marker full flow

Congratulations! You’ve been capable of create a geo marker with a polygon. You may reset the map and draw as many polygons as you need.

Writing Map UI Assessments

Assessments are normally necessary in any piece of software program. Google Map Compose library was not left behind when it comes to writing checks on your map logic. To make it extra attention-grabbing, it’s simpler so that you can write the UI checks on your map composables.

Head over to your androidTest listing and open GoogleMapTest.kt. The take a look at class GoogleMapTest solely has a helpful setup technique that runs earlier than your checks run. It initializes a CameraPositionState with a location and a zoom degree.

Earlier than writing your checks, it is advisable to arrange your map. Add the next technique under the setup technique:

personal enjoyable loadMap() {
  val countDownLatch = CountDownLatch(1)
  composeTestRule.setContent {
        modifier = Modifier.fillMaxSize(),
        cameraPositionState = cameraPositionState,
        onMapLoaded = {
  val mapLoaded = countDownLatch.await(30, TimeUnit.SECONDS)
  assertTrue("Map loaded", mapLoaded)

Substitute your imports on the prime with:

import androidx.compose.basis.structure.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.take a look at.junit4.createComposeRule
import junit.framework.Assert.assertTrue
import org.junit.Earlier than
import org.junit.Rule
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

You’ve gotten a CountDownLatch to permit ready for the map to load earlier than doing any operation on the map. You set the content material of your display screen with the composeTestRule. Within the setContent lambda, you add the GoogleMap composable. You additionally move the cameraPositionState modifier, and inside your onMapLoaded, you begin your countdown.

Lastly, you carry out an assertion after ready 30 seconds to examine whether or not the map was loaded. You’ll use this technique to initialize your map in consecutive checks.

You’ll now add checks to point out the digital camera place and map zoom degree are set to the right values.

Add the next checks:

enjoyable testCameraPosition() {
enjoyable testZoomLevel() {

Within the code above, you’ve got two checks: one for testing the digital camera place and the opposite for testing the zoom degree of your map. In every of those checks, you name loadMap() after which assert that the place and zoom degree on the map is much like your preliminary location. Run the take a look at.

Google Map UI Tests

You may see all of your checks run efficiently!

The place to Go From Right here?

Obtain the ultimate challenge by clicking Obtain Supplies on the prime or backside of the tutorial.

You may discover the drawing polyline choice to display somebody strolling by a discipline. You may maybe add extra checks to check your map-related functionalities.

Take a look at the official Google Maps Compose documentation to be taught extra about maps in Compose. To be taught extra about testing your compose layouts, checkout the official testing documentation.

Hopefully, you loved this tutorial. If in case you have any questions or feedback, please be part of the discussion board dialogue under!

Related Articles


Please enter your comment!
Please enter your name here

Latest Articles