DEV Community

Cover image for W1 D1: Adding a Google Map πŸ—ΊοΈπŸ’—
Chitranshi Srivastava
Chitranshi Srivastava

Posted on

W1 D1: Adding a Google Map πŸ—ΊοΈπŸ’—

Hi reader! I'm an Android apps developer. I'm starting this new series called #100DaysOfAndroid in which I'll be covering a cool concept in Android every day for 100 days πŸ”₯. This series will basically have posts about something that I implement during the day & think is an important topic to explain here for your as well as my future reference. Expect a mixture of easy, medium & advanced topics to be covered in these posts. Hopefully, this series helps & motivates you in your journey as an Android developer! πŸ‘‰πŸ‘ˆ

Week 1 πŸ—ΊοΈ

This week we'll be doing all things maps in Android. Being able to pull off stunts like adding markers to the map, style the map, add geofences, get the user's last known location, etc. are indispensable to your knowledge in this area (pun intended). These things are extremely useful & are super important if you want to know how to add functionalities like sharing your location, sending notifications according to the user's location, etc.

You can check out the other posts from this week πŸ“ πŸ‘.

  1. Adding a Google Map
  2. Extracting & Saving the User's Current Location
  3. Incremental Location Permissions
  4. Incremental Location Permissions with EasyPermissions Library
  5. Sharing Location Data using Firebase
  6. Live Location Tracking/Sharing
  7. Adding a Marker to the Map on Long-click & Storing the Marked Location/POI

Day 1: Add a Google Map to Your App

Create a Google Maps project

  • Add Google Maps to your Project
    • New project β†’ Google Maps Activity -> ... -> Create
    • This will add all the code necessary for adding a map to your app. It mainly adds 3 files automatically to your project: a MapsActivity, an activity_maps.xml layout file in the res folder & an activity_maps_api.xml resource file in the values folder.

You don't need to add the code below. As soon as you create the project, Android Studio will add these for you.

// MapsActivity.kt

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.gmail.apigeoneer.sharemylocation.databinding.ActivityMapsBinding

/**
 * Once an instance of this interface is set on a MapFragment or MapView object, onMapReady(GoogleMap) method is triggered
 * when the map is ready to be used and provides a non-null instance of GoogleMap.
 */
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

    // Declare a map object
    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)
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services are not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    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))
    }
}
Enter fullscreen mode Exit fullscreen mode
// activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    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" />
Enter fullscreen mode Exit fullscreen mode
// google_maps_api.xml (debug)

<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=...

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

    Package name:
    ...

    SHA-1 certificate fingerprint:
    ...
    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.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">YOUR_API_KEY</string>
</resources>
Enter fullscreen mode Exit fullscreen mode

If you're wondering if you need to add any dependencies for this code to run successfully, the answer is no you don't.

  • Now, you just need to provide the API key.

Create a new project on Google Cloud

  • Go over to the Google Cloud page β†’ Create a new project
    1.png
    2.png

  • Enable the Maps SDK for Android
    0.png

  • Credentials β†’ Create Credentials β†’ API key β†’ Restrict key β†’ Android apps, Restrict key, Maps SDK for Android (Select APIs) β†’ save β†’ copy key
    5.png
    3.png
    6.png
    7.png

  • Save.

Add the API key to your app

  • Paste the key in place of YOUR_KEY_HERE
      // google_maps_api.xml


<stringname="google_maps_key"templateMergeStrategy="preserve"translatable="false">YOUR_KEY_HERE</string>
Enter fullscreen mode Exit fullscreen mode

Now run the app & a beautiful map with a marker in Sydney should appear once the app installs on your device/emulator.
54.png

Oldest comments (0)