Google Map - How to load Google Maps in Android using Kotlin.

Last updated Dec 21, 2021


In this android example tutorial, we will learn how to load google maps in android studio using kotlin language. Android Studio is the recommended development environment for building an app with the Maps SDK for Android.

Implementation: 

Step 1. 
Create a new Project in android studio.

Go to File > New > New Project > Google Maps Activity > Next > Enter Name > Select Language Kotlin > Finish.

 

After creating the new project, Android Studio starts Gradle and builds your project, which may take a few seconds.

Android Studio opens the google_maps_api.xml and the MapsActivity.kt files in the editor. Notice that the google_maps_api.xml file contains instructions for getting a Google Maps API key before running the application.

Step 2. Getting a Google Maps API key
To access Google Maps we need an API key.  Let's create Google Maps API key

First way to get Google Api Key:

Use the link provided in the google_maps_api.xml file that Android Studio created for you:

Please copy the link provided in the google_maps_api.xml file and paste it into your browser. The link takes you to the Google Cloud Platform Console and 
supplies the required information to the Google Cloud Platform Console via URL parameters, thus reducing the manual input required.
 

Android Google Maps



Perform these specific tasks in your browser screen to achieve Api Key:
 

Next > enable > Create new Api key


Your api key is created now you will see the output:

Android Google Maps  Markers


 

After this you will have a new Api key which will be started from "AIza". Copy that key and paste inside google_maps_api.xml file.
 

Android Google Maps Infowindow


Second way to achieve Google Api Key: 

Copy the credentials details provided in the google_maps_api.xml file.

Now go to the Google Cloud Platform Console using below link.

https://console.cloud.google.com/

 

Use the copied credentials to create a new API key or add your app to an existing API key.

Step 3. Look at the code 

activity_maps.xml file

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

MapsActivity.kt file

To get hold of the GoogleMap object in our MapsActivity class we need to implement the OnMapReadyCallback interface and override the onMapReady callback method.
Adding markers on the Google Map 

 

val sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))



Full code of MapsActivity.kt file

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 sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}


Here LatLng is the Latitude and Longitude which is used for the location. As we see the values inside LatLng method we can customize the positions. In this example
we are using sydney latitude and longitude, you can enter your current latitude & longitude and find your LatLng on google by enter a query (LatLng of (Your city) name).
 

Step 4. Build and Run your app in real device (Sometimes emulator not supports the Google Play Services) and get the following output.

OUTPUT:

Android Google Maps  2

 

Android Google Maps Click events


 

Complete Source Code of Google Maps in Android Example:

activity_maps.xml file


<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity" />

 

MapsActivity.kt file

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.nishajain.googlemap.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 sydney = LatLng(-34.0, 151.0)
        mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
    }
}

 

google_maps_api.xml file

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=D1:3E:95:7E:B9:3D:65:FA:C5:11:DB:86:D9:34:CA:E7:70:DE:36:17%3Bcom.nishajain.googlemap

    You can also add your credentials to an existing key, using these values:

    Package name:
    com.nishajain.googlemap

    SHA-1 certificate fingerprint:
    D1:3E:95:7E:B9:3D:65:FA:C5:11:DB:86:D9:34:CA:E7:70:DE:36:17

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    //Please add your api key here.
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">AIzaSyCDVGMpqMH-9laN4AWEDfAOIwsINmo3aWU</string>
</resources>

 

 

build.gradle(app) file

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.googlemap"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'com.google.android.gms:play-services-maps:18.0.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

 

Conclusion: In this article we have covered how to implement google maps in Android apps using Kotlin language.


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

47 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions