Thursday, April 25, 2024
HomeProgrammingMaps Compose Library Tutorial for Android: Getting Began

Maps Compose Library Tutorial for Android: Getting Began


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

Nonetheless, it will get difficult while you need to use the previous library, Maps SDK for Android, with Jetpack Compose. You will need to write advanced and sometimes giant View interoperability code blocks to mix Jetpack Compose with the usual map UI element – MapView. This opposes one in every of Jetpack Compose’s main goals of being easy and exact. To resolve this, Google created a brand new and easier approach of dealing with Google Maps in Jetpack Compose tasks.

In February 2022, Google launched the Maps Compose library. It’s an open-source set of composable features that simplify Google Maps implementation. In addition to that, the library accommodates particular knowledge varieties 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 data 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 study:

  • Establishing Google Maps in compose.
  • Requesting location permissions.
  • Including markers, data 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 undertaking by clicking Obtain Supplies on the prime or backside of the tutorial.

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

App first run screen

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

Setting Up

To start out engaged on maps in compose, you will need to full the next steps:

  1. Establishing the dependencies:
  2. 
      implementation 'com.google.maps.android:maps-compose:2.4.0'
      implementation 'com.google.android.gms:play-services-maps:18.1.0'
      implementation 'com.google.android.gms:play-services-location:20.0.0'
    

    The primary is the Maps Compose library, and the opposite two are the Play Providers maps SDK and site SDKs. Notice that these dependencies exist already within the starter undertaking, so there’s no have to 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 one can get your key right here. After getting your key, proceed so as to add it to your native.properties file as follows:
    
    MAPS_API_KEY=YOUR_API_KEY
    

Now that you’ve got every part set, time to get your fingers soiled with maps in compose. You’ll begin by requesting location permissions to 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. Change //TODO Add Permissions with:


// 1
val scope = rememberCoroutineScope()
// 2
val context = LocalContext.present
// 3
var showMap by rememberSaveable {
  mutableStateOf(false)
}
// 4
PermissionDialog(
    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!")
      }
      fetchLocationUpdates.invoke()
    }
  }
}

To resolve errors, substitute 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 com.android.composegeomarker.R
import com.android.composegeomarker.permissions.PermissionAction
import com.android.composegeomarker.permissions.PermissionDialog
import kotlinx.coroutines.launch

Right here’s what the code above does:

  1. You create a CoroutineScope variable you’ll use to indicate your Snackbar.
  2. This can be a variable to get the context of your present composable.
  3. You could have a Boolean variable showMap that represents whether or not the app has mandatory 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 consumer has chosen. It may possibly both be PermissionGranted or PermissionDenied. On every of this, you replace the showMap variable. When the consumer grants the permission, you present a Snackbar with a “Location permission granted!” message and begin the situation updates.

With this, you’re prepared to indicate areas on a map, and that’s the subsequent 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, substitute 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
import com.google.android.gms.maps.mannequin.CameraPosition
import com.google.android.gms.maps.mannequin.LatLng
import com.google.maps.android.compose.GoogleMap
import com.google.maps.android.compose.rememberCameraPositionState

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 to your map. On this case, you set your map’s location and zoom degree.

Second, substitute // TODO Add Google Map with:


GoogleMap(
    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState
)

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

Final, you’ll want to name your customized MapView composable in your MapScreenContent.kt. You cross within the context and site as parameters. For an instance, you’ll use a hard and fast location in Singapore. Return to presentation/screens/MapScreenContent.kt and beneath 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.


import com.android.composegeomarker.presentation.composables.MapView
import com.google.android.gms.maps.mannequin.LatLng

Right here, you added the conditional to verify whether or not your map needs to 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 situation 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:


Marker(
    state = MarkerState(place = location),
)

Add any lacking imports by urgent Choice-Return on a Mac or Alt-Enter on a Home windows PC. Your last outcome will probably be:


GoogleMap(
    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState
) {
  Marker(
      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 akin to its place and data window.

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

Singapore marker

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

Typically, you’ll want to indicate data when a consumer faucets a marker. For that, you’ll have so as to add InfoWindow to your map, which you’ll study subsequent.

Displaying Map Info Home windows

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


val infoWindowState = rememberMarkerState(place = location)

You could have now created a state variable for the marker properties and handed the situation to this marker.

Subsequent, beneath your Marker composable, add:


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

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

Construct and run the app. Faucet the Singapore marker, and it’s best 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

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

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


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

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

Circle is yet one more map baby composable and has a number of parameters. For this tutorial, you solely have to 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.

To this point, you’ve drawn a number of shapes in your map. Within the subsequent part, you’ll learn 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 upon getting a map ID.
  2. JSON based mostly styling: Right here, you create a map fashion on the previous fashion wizard . When you full the customization, you possibly can 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 previous fashion wizard. You must see:

JSON map styling wizard

On the left, you have got customization choices akin to altering the density of the options and altering the theme of your map.

Begin by choosing the Silver theme as proven beneath:

Wizard with silver-theme styling

On the best facet, you possibly can see the map shade adjustments to mirror the chosen theme. Subsequent, click on MORE OPTIONS as proven above.

Styling wizard with more customization options

This exhibits an inventory of options you possibly can customise and visualize on the map. For this tutorial, you’ll customise the Street characteristic.

Observe these steps:

  • Click on the Street characteristic, which is able to open up the component kind part on the best.
  • The weather kind part has an inventory of components you possibly can 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 Model dialog as proven:

Styling wizard export style

Click on COPY JSON choice. This copies the JSON fashion in your clipboard. You’re now just a few 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 have got the fashion prepared to be used. Subsequent, you’ll want to apply it to your map.

Making use of Customized Model to Your Map

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


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

Add any lacking imports by urgent Choice-Return on a Mac or Alt-Enter on a PC. As seen above, you create a brand new state variable of kind MapProperties. This variable holds properties you possibly can change on the map. You cross the customized fashion to the mapStyleOptions, which hundreds the fashion from the uncooked listing.

Subsequent, add this variable mapProperties as properties parameter to your GoogleMap. Your last outcome needs to be:


GoogleMap(
    modifier = Modifier.fillMaxSize(),
    cameraPositionState = cameraPositionState,
    properties = mapProperties
) {
  // Baby 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

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

A standard characteristic of maps on gadgets is the power for them to replace in actual time. To try 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:


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

  awaitClose {
    removeLocationUpdates(callback)
  }
}

Right here, you wrap your LocationCallback in a callbackFlow. Within the callbackFlow, callback known as every time you have got location updates from requestLocationUpdates. And eventually, 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:


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

This makes use of repeatOnLifecycle() to gather safely out of your Move within the UI. You additionally cross the situation to your viewmodel to share the newest worth along 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 employ the situation replace characteristic to attract polylines as a consumer walks in a sure space. You draw polylines after a consumer 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 have got a GeoMarkerScreen composable that has a number of map state variables outlined. It has a Scaffold inside the place you have got your GoogleMap composable. You could have three TODOs you’ll deal with 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, substitute // TODO Add click on listener with:


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

Right here, you do a conditional verify to verify whether or not the polygon is already drawn. When the situation isn’t happy, you replace the showSavePoint, which is a Boolean that determines whether or not to indicate the UI to save lots of the clicked level. Clicking a map additionally returns a LatLng of the clicked level. You assign this worth to the clickedLocation variable.

Subsequent, substitute // TODO Save Level UI with:


if (showSavePoint) {
  SaveGeoPoint(latLng = clickedLocation) {
    showSavePoint = it.hideSavePointUi
    areaPoints.add(it.level)
  }
} else {
  if (areaPoints.isEmpty()) {
    Textual content(
        modifier = Modifier
            .fillMaxWidth(),
        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 Choice-Return on a Mac or Alt-Enter on a PC. You add one other conditional verify.

When showSavePoint is true, you present the SaveGeoPoint composable. SaveGeoPoint is a customized composable with UI for saving the clicked level. You cross the clickedLocation from the map click on listener. When the situation evaluates to false, you present a textual content with directions on how one 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 save lots of the purpose in your map. It shows the LatLng and the Save Level motion which saves your level.

You’ll discover while you save three factors that the Full button on the backside turns into energetic. 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.

Change // TODO Add Polygon with:


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

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

Right here’s what the code above does:

  1. This can be a conditional verify to verify whether or not the polygon is drawn. You additionally verify 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 checklist, you add a marker in your map.
  3. You employ Polygon composable, to attract your polygon. You cross within the factors to attract and the colours to your polygon.
  4. This can be 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 Checks

Checks are often vital in any piece of software program. Google Map Compose library was not left behind by way of writing checks to your map logic. To make it extra attention-grabbing, it’s simpler so that you can write the UI checks to your map composables.

Head over to your androidTest listing and open GoogleMapTest.kt. The check class GoogleMapTest solely has a useful setup methodology that runs earlier than your checks run. It initializes a CameraPositionState with a location and a zoom degree.

Earlier than writing your checks, you’ll want to arrange your map. Add the next methodology beneath the setup methodology:


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

Change your imports on the prime with:


import androidx.compose.basis.structure.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.check.junit4.createComposeRule
import com.google.android.gms.maps.mannequin.CameraPosition
import com.google.android.gms.maps.mannequin.LatLng
import com.google.maps.android.compose.CameraPositionState
import com.google.maps.android.compose.GoogleMap
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 could have 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 with the composeTestRule. Within the setContent lambda, you add the GoogleMap composable. You additionally cross the cameraPositionState modifier, and inside your onMapLoaded, you begin your countdown.

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

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

Add the next checks:


@Check
enjoyable testCameraPosition() {
  loadMap()
  assertEquals(singapore, cameraPositionState.place.goal)
}
@Check
enjoyable testZoomLevel() {
  loadMap()
  assertEquals(cameraZoom, cameraPositionState.place.zoom)
}

Within the code above, you have 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 check.

Google Map UI Tests

You may see all of your checks run efficiently!

The place to Go From Right here?

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

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

Try the official Google Maps Compose documentation to study extra about maps in Compose. To study extra about testing your compose layouts, checkout the official testing documentation.

Hopefully, you loved this tutorial. You probably have any questions or feedback, please be part of the discussion board dialogue beneath!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments