Skip to content
Related Articles
Open in App
Not now

Related Articles

Android Jetpack Compose: How to Add SearchView to Google Maps

Improve Article
Save Article
  • Last Updated : 23 Jan, 2023
Improve Article
Save Article

We have seen the implementation of Google Maps in Android along with markers on it. But many apps provide features so that users can specify the location on which they have to place markers. So in this article, we will implement a SearchView in our Android app so that we can search a location name and add a marker to that location. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 


package com.example.newcanaryproject.ui.theme
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)

Step 3: Adding dependency to use Google Maps

Navigate to build.gradle file and add the below dependency in the build.gradle file.


After adding the dependency simply click on the sync now option to install it.

Step 4: Adding permissions and google maps API key

Navigate to app>AndroidManifest.xml file and add the below code in the application tag for adding the API key. 


  android:value="Enter your API key" />

Check out the below article on How to generate API key for Google Maps in Android.

Step 5: Create a new layout file for the map layout

Navigate to app>res>Right click on it>New>Directory and name it as layout. Now right-click on that directory and click on New>Layout resource file. Create a new xml file and name it map_layout and add the below code to it. Comments are added in the code to get to know it in detail. 


<?xml version="1.0" encoding="utf-8"?>
    android:layout_height="match_parent" />

Step 6: Create a new file for creating a Map

Navigate to app>java>your app’s package name>Right click on it>New>Kotlin class and name it as MapUtils and add the below code to it. Comments are added in the code to get to know it in detail. 


package com.example.newcanaryproject
import android.os.Bundle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
// on below line creating a new
// composable widget for displaying map
fun rememberMapViewWithLifecycle(): MapView {
    val context = LocalContext.current
    // on below line initializing our maps view with id.
    val mapView = remember {
        MapView(context).apply {
            id =
    // Makes MapView follow the lifecycle of this composable
    val lifecycleObserver = rememberMapLifecycleObserver(mapView)
    // on below line initializing lifecycle variable.
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    // on below line adding observer for lifecycle.
    DisposableEffect(lifecycle) {
        onDispose {
    // returning map view on below line.
    return mapView
// creating a function for map lifecycle observer.
fun rememberMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
    remember(mapView) {
        // on below line adding different events for maps view
        LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> mapView.onCreate(Bundle())
                Lifecycle.Event.ON_START -> mapView.onStart()
                Lifecycle.Event.ON_RESUME -> mapView.onResume()
                Lifecycle.Event.ON_PAUSE -> mapView.onPause()
                Lifecycle.Event.ON_STOP -> mapView.onStop()
                Lifecycle.Event.ON_DESTROY -> mapView.onDestroy()
                else -> throw IllegalStateException()

Step 7: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.


package com.example.newcanaryproject
import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.example.newcanaryproject.ui.theme.NewCanaryProjectTheme
import com.example.newcanaryproject.ui.theme.greenColor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
    var message = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        setContent {
            NewCanaryProjectTheme {
                // on below line we are specifying background color for our application
                    // on below line we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    // on the below line we are specifying
                    // the theme as the scaffold.
                        // in scaffold we are specifying the top bar.
                        topBar = {
                            // inside top bar we are specifying background color.
                            TopAppBar(backgroundColor = greenColor,
                                // along with that we are specifying
                                // title for our top bar.
                                title = {
                                    // in the top bar we are
                                    // specifying tile as a text
                                        // on below line we are specifying
                                        // text to display in top app bar.
                                        text = "GFG",
                                        // on below line we are specifying
                                        // modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
                                        // on below line we are specifying
                                        // text alignment.
                                        textAlign = TextAlign.Center,
                                        // on below line we are specifying
                                        // color for our text.
                                        color = Color.White
                        }) {
                        // on below line we are calling
                        // method to display UI
fun mapUI(context: Context) {
    val mapView = rememberMapViewWithLifecycle()
    // on below line creating a variable for location.
    val locationName = remember {
    // on below line creating a column for our maps.
        modifier = Modifier
    ) {
            modifier = Modifier
                .padding(all = 3.dp),
            horizontalArrangement = Arrangement.Center
        ) {
            // on below line we are creating a
            // text field for our message number.
                // on below line we are specifying value
                // for our message text field.
                value = locationName.value,
                // on below line we are adding on
                // value change for text field.
                onValueChange = { locationName.value = it },
                // on below line we are adding place holder
                // as text as "Enter your email"
                placeholder = { Text(text = "Enter your location to search") },
                // on below line we are adding modifier to it
                // and adding padding to it and filling max width
                modifier = Modifier
                // on below line we are adding text style
                // specifying color and font size to it.
                textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
                // on below line we are adding single line to it.
                singleLine = true,
            Spacer(modifier = Modifier.width(5.dp))
            // on below line adding a button.
                onClick = {
                    getMapLocation(locationName.value, context, mapView)
                // on below line adding a modifier for our button.
                modifier = Modifier.padding(3.dp)
            ) {
                    // on below line we are specifying the drawable
                    // image for our image.
                    painter = painterResource(id = R.drawable.ic_search),
                    alignment = Alignment.Center,
                    // on below line we are specifying
                    // content description for our image
                    contentDescription = "Image",
                    // on below line we are setting height
                    // and width for our image.
                    modifier = Modifier
        // on below line adding a map view to it.
        AndroidView({ mapView }) { mapView ->
            // on below line launching our map view
            CoroutineScope(Dispatchers.Main).launch {
                val map = mapView.awaitMap()
                // on below line adding zoom controls for map.
                map.uiSettings.isZoomControlsEnabled = true
private fun getMapLocation(location: String, context: Context, mapView: MapView) {
    // below line is to create a list of address
    // where we will store the list of all address.
    var addressList: List<Address>? = null
    // on below line we are getting our map view.
    mapView.getMapAsync {
        if (location != null || location == "") {
            // on below line we are creating
            // and initializing a geo coder.
            val geocoder = Geocoder(context)
            try {
                // on below line we are getting location from the
                // location name and adding that location to address list.
                addressList = geocoder.getFromLocationName(location, 1)
            } catch (e: IOException) {
            // on below line we are getting the location
            // from our list a first position.
            val address: Address = addressList!![0]
            // on below line we are creating a variable for our location
            // where we will add our locations latitude and longitude.
            val latLng = LatLng(address.getLatitude(), address.getLongitude())
                ).title("Marker in " + location)
            // below line is use to move camera.
            // on below line we are moving our
            // camera at the focused location
                    latLng, 8f

Now run your application to see its output of it. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!