Building Android Apps with Kotlin: Utilizing Google Maps

In modern mobile application development, map functionality has become an essential component. Especially for apps that provide location-based services (e.g., food delivery, travel guides, etc.), using Google Maps is very useful. In this tutorial, we will detail how to implement Google Maps in Android apps using Kotlin.

1. Understanding the Google Maps API

The Google Maps API is a service that allows developers to integrate Google Maps into their applications. Through this API, various features such as location display, route navigation, and user current location can be utilized.

2. Setting Up Android Studio Environment

To integrate Google Maps into your Android app, you first need to set up the development environment. Let’s start a new project using Android Studio.

  1. Open Android Studio and create a new project.
  2. When creating the project, select Empty Activity.
  3. After setting the project name and package name, proceed to the next step.

3. Obtaining the Google Maps API Key

You need an API key to use Google Maps. Here, I will explain how to obtain the API key.

  1. Visit the Google Cloud Platform and create a new project.
  2. Activate the Maps API in the API & Services menu.
  3. Create an API key, which you will use to send requests.
  4. Add the API key to the res/values/strings.xml file:
<string name="google_maps_key">YOUR_API_KEY</string>

4. Adding Dependencies to Gradle

You need to add the necessary dependencies to the build.gradle file to use Google Maps.

dependencies {
    implementation 'com.google.android.gms:play-services-maps:17.0.1'
}

5. Creating XML Layout File

To display the map in the app, you can add a MapView or SupportMapFragment to the XML layout file. Here, we will use SupportMapFragment. Create the res/layout/activity_maps.xml file as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </fragment>

</RelativeLayout>

6. Creating Map Activity

Now, it’s time to create an activity to display Google Maps. Create the MapsActivity.kt file as follows:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
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

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    private lateinit var mMap: GoogleMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)

        // 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))
    }
}

7. Requesting App Permissions

To use location information, you need to add the required permissions to the app’s AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
    ... >
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />
</application>

8. Displaying Current Location on Map

Let’s add functionality to display the current location on the app. Add the code to enable user location in the onMapReady method:

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // If permission is not granted
    ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 1000)
    return
}
mMap.isMyLocationEnabled = true

9. Pinpointing User Location

In addition to adding the basic location, you can implement functionality to pin a specific location when the user selects it. Add the following code to the onMapClickListener method:

mMap.setOnMapClickListener { latLng ->
    mMap.addMarker(MarkerOptions().position(latLng).title("Selected Location"))
}

10. Additional API Features

The Google Maps API provides various features beyond simple map display. For example, drawing routes, adding multiple markers, or creating custom markers. Below is an example of creating a custom marker:

val bitmap = BitmapFactory.decodeResource(resources, R.drawable.custom_marker)
val markerOptions = MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromBitmap(bitmap))
mMap.addMarker(markerOptions)

11. Testing and Deployment

Once the app is complete, you can test it on an emulator or a real device. After ensuring there are no issues, you will prepare it for distribution on the Play Store. To distribute, create an APK file and upload it via the Play Console.

Conclusion

In this tutorial, we learned how to utilize Google Maps in Android apps using Kotlin. The Google Maps API offers various and powerful features, so take advantage of it to develop location-based services. Through various examples and exercises, we hope you become a better developer.

If you found this tutorial helpful, please share it and leave a comment! We are preparing a series of more Android development tutorials, so stay tuned.