Introduction to Google Map API with Jetpack

This is a guide on how to integrate Google Maps Sdk to an Android application using Kotlin and Jetpack Compose.

· 6 min read
Wilson Ochieng

Wilson Ochieng

Android Expert developing mobile applications with 4+ Years of Experience.

topics

Introduction

Maps greatly improve user experience in today's mobile applications, particularly for those that primarily rely on location-based services. One of the most popular mapping services is Google Maps, which provides developers with easy-to-use, robust, and extensive APIs for integrating maps into their apps. Combined with Google's state-of-the-art framework for creating native Android UIs, Jetpack Compose, you can quickly and easily create interactive and fluid map experiences.

Jetpack Compose leverages strong tools, intuitive Kotlin APIs, and minimal code to streamline and accelerate Android UI development. The flexibility of Google's mapping technologies and the power of declarative UI are combined when Google Maps and Jetpack Compose are integrated. With this combination, developers may create feature-rich applications that provide route planning, real-time location tracking, and other features.

This article will walk you through the process of utilizing Kotlin with Jetpack Compose to integrate the Google Map API into an Android application. From project setup and dependency configuration to map view creation and marker addition, we will cover it all. As a clear and useful illustration of the procedures involved, we will use the addition of a marker to Nairobi as our example.

By the end of this tutorial, you should have a firm grasp on how to integrate Google Maps in Jetpack Compose and how to improve your Android applications' usability and functionality.

Prerequisites

- Basic knowledge of Kotlin, Jetpack Compose, and Android development

What you will need

  • Android Studio: Latest stable version installed.
  • Google API Key: Obtained from the Google Cloud Console by enabling the Maps SDK for Android(Billing enabled).
  • An Android device or an Android emulator that runs the Google APIs platform based on Android 5.0 or higher.

Step 1: Setting Up Your Project

- Create a New Project: Open Android Studio and start a new project by selecting No Activity template.

Image

- Give the project a suitable name,select Kotlin language and then create the project.

Image

Step 2:Add the Google Maps Views Activity

- Right-click on the app folder in your project.

- Choose New > Google > Google Maps Views Activity.

- In the New Android Activity dialog box, select the Launcher Activity checkbox.

- Select Finish.

Image

MapsActivity file contains the markers of the location you have chosen and can be modified to point to any other location.

Image


package com.example.mygooglemaps

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.example.mygooglemaps.databinding.ActivityMapsBinding

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityMapsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val kenya = LatLng(-1.286389, 36.817223)
        mMap.addMarker(MarkerOptions().position(kenya).title("Marker in Nairobi"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(kenya))
    }
}

Step 3:Get Google Api Keys

Image

Step 4: Setting Up the Map

It is advisable that you use Secrets Gradle Plugin for Android in your build.gradle by configuring the app level and module level build.gradle files.

App level build.gradle file

package com.example.mygooglemaps

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.example.mygooglemaps.databinding.ActivityMapsBinding

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityMapsBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMapsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        // Add a marker in Sydney and move the camera
        val kenya = LatLng(-1.286389, 36.817223)
        mMap.addMarker(MarkerOptions().position(kenya).title("Marker in Nairobi"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(kenya))
    }
}

Module Level build.gradle


// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    alias(libs.plugins.android.application) apply false
    alias(libs.plugins.jetbrains.kotlin.android) apply false
    alias(libs.plugins.google.android.libraries.mapsplatform.secrets.gradle.plugin) apply false

}

- Add the following code after opening the secrets.properties file in your top-level directory.If the file does not exist,create it. Change YOUR_API_KEY to reflect your API key.

MAPS_API_KEY=YOUR_API_KEY

- Save the file.

- In your top-level directory, create a local.defaults.properties file in the same location as the secrets.properties file, and then add the following code to it then save it.

MAPS_API_KEY=DEFAULT_API_KEY

- Add API Key: In the AndroidManifest.xml, add your Google Maps API key inside the <application> tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyGoogleMaps"
        tools:targetApi="31">
            <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY" />

        <activity
            android:name=".MapsActivity"
            android:exported="true"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

- Open your module-level build.gradle or build.gradle.kts file in Android Studio, then modify the secrets property. Add the secrets property if it is not already there.


secrets {
    // Optionally specify a different file name containing your secrets.
    // The plugin defaults to "local.properties"
    propertiesFileName = "secrets.properties"

    // A properties file containing default secret values. This file can be
    // checked in version control.
    defaultPropertiesFileName = "local.defaults.properties"

    // Configure which keys should be ignored by the plugin by providing regular expressions.
    // "sdk.dir" is ignored by default.
    ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
    ignoreList.add("sdk.*")       // Ignore all keys matching the regexp "sdk.*"
}

- This application's XML layout file, activity_maps.xml, specifies how the user interface should be organized. In the res/layout directory is where you get the file.
- MapsActivity, which is specified in the maps activity file, is the default activity of the fragment when tools:context is used.

- As the fragment type used in the maps activity file, android:name sets the fragment's class name to SupportMapFragment.
- The XML Layout contains this code


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyGoogleMaps"
        tools:targetApi="31">
            <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="Your Api Key" />

        <activity
            android:name=".MapsActivity"
            android:exported="true"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Step 5:Deploy and run the app

When you run the application,it will display the map of the location whose latitude and longitude are embedded in the code with a marker.

Image


Conclusion

Integrating Google Maps into an Android application using Kotlin and Jetpack Compose provides a modern and efficient approach to displaying maps and markers. This tutorial walked you through setting up a new project, adding necessary dependencies, configuring your Google Maps API key, and creating a map with a marker. With this setup, you can further customize your maps, add more markers, and enhance your application’s functionality.

Understanding and implementing Google Maps in Jetpack Compose can significantly improve user experience, especially in applications requiring location-based services. This integration not only simplifies the development process but also ensures that your app stays current with modern Android development practices. Start exploring the numerous possibilities that come with Google Maps and Jetpack Compose to create more dynamic and interactive applications.


share

Wilson Ochieng

Android Expert developing mobile applications with 4+ Years of Experience.